Skip to content

Commit 4b9dbed

Browse files
authored
Merge branch 'main' into update-modelid
2 parents 9da9b38 + aa62b14 commit 4b9dbed

76 files changed

Lines changed: 1791 additions & 1690 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎dotnet/samples/KernelSyntaxExamples/Example30_ChatWithPrompts.cs‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,9 @@ public static async Task RunAsync()
3838
Console.WriteLine("======== Chat with prompts ========");
3939

4040
/* Load 3 files:
41-
* - 28-system-prompt.txt: the system prompt, used to initialize the chat session.
42-
* - 28-user-context.txt: the user context, e.g. a piece of a document the user selected and is asking to process.
43-
* - 28-user-prompt.txt: the user prompt, just for demo purpose showing that one can leverage the same approach also to augment user messages.
41+
* - 30-system-prompt.txt: the system prompt, used to initialize the chat session.
42+
* - 30-user-context.txt: the user context, e.g. a piece of a document the user selected and is asking to process.
43+
* - 30-user-prompt.txt: the user prompt, just for demo purpose showing that one can leverage the same approach also to augment user messages.
4444
*/
4545

4646
var systemPromptTemplate = EmbeddedResource.Read("30-system-prompt.txt");
@@ -58,13 +58,13 @@ public static async Task RunAsync()
5858
// Adding required arguments referenced by the prompt templates.
5959
var arguments = new KernelArguments
6060
{
61-
// Put the selected document into the variable used by the system prompt (see 28-system-prompt.txt).
61+
// Put the selected document into the variable used by the system prompt (see 30-system-prompt.txt).
6262
["selectedText"] = selectedText,
6363

64-
// Demo another variable, e.g. when the chat started, used by the system prompt (see 28-system-prompt.txt).
64+
// Demo another variable, e.g. when the chat started, used by the system prompt (see 30-system-prompt.txt).
6565
["startTime"] = DateTimeOffset.Now.ToString("hh:mm:ss tt zz", CultureInfo.CurrentCulture),
6666

67-
// This is the user message, store it in the variable used by 28-user-prompt.txt
67+
// This is the user message, store it in the variable used by 30-user-prompt.txt
6868
["userMessage"] = "extract locations as a bullet point list"
6969
};
7070

‎dotnet/samples/KernelSyntaxExamples/Example59_OpenAIFunctionCalling.cs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,11 @@ public static async Task RunAsync()
2020
{
2121
// Create kernel.
2222
IKernelBuilder builder = Kernel.CreateBuilder();
23-
builder.AddOpenAIChatCompletion(TestConfiguration.OpenAI.ChatModelId, TestConfiguration.OpenAI.ApiKey);
23+
24+
// We recommend the usage of OpenAI latest models for the best experience with tool calling.
25+
// i.e. gpt-3.5-turbo-1106 or gpt-4-1106-preview
26+
builder.AddOpenAIChatCompletion("gpt-3.5-turbo-1106", TestConfiguration.OpenAI.ApiKey);
27+
2428
builder.Services.AddLogging(services => services.AddConsole().SetMinimumLevel(LogLevel.Trace));
2529
Kernel kernel = builder.Build();
2630

@@ -39,7 +43,7 @@ public static async Task RunAsync()
3943
"Sydney" => "75 and sunny",
4044
"Tel Aviv" => "80 and sunny",
4145
_ => "31 and snowing",
42-
}, "GetWeatherForCity", "Gets the current weather for the specified city"),
46+
}, "Get_Weather_For_City", "Gets the current weather for the specified city"),
4347
}));
4448

4549
Console.WriteLine("======== Example 1: Use automated function calling with a non-streaming prompt ========");
@@ -106,9 +110,9 @@ public static async Task RunAsync()
106110

107111
while (true)
108112
{
109-
Console.Write("Question: ");
113+
Console.Write("Question (Type \"quit\" to leave): ");
110114
string question = Console.ReadLine() ?? string.Empty;
111-
if (question == "done")
115+
if (question == "quit")
112116
{
113117
break;
114118
}
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/IntegrationTests/TestSettings/PlannerConfiguration.cs‎

Lines changed: 0 additions & 20 deletions
This file was deleted.

‎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
}

‎python/.coveragerc‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
[run]
22
source = semantic_kernel
33
omit =
4-
semantic_kernel/connectors/*
4+
semantic_kernel/connectors/memory/*
5+
semantic_kernel/connectors/openapi/*
6+
semantic_kernel/connectors/search_engine/*
7+
semantic_kernel/connectors/ai/google_palm/*
8+
semantic_kernel/connectors/ai/hugging_face/*
9+
510

611
[report]
712
# Regexes for lines to exclude from consideration
@@ -18,4 +23,5 @@ exclude_lines =
1823

1924
# TYPE_CHECKING and @overload blocks are never executed during pytest run
2025
if TYPE_CHECKING:
21-
@overload
26+
@overload
27+
@abstractmethod

0 commit comments

Comments
 (0)