Skip to content
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

.Net: Adding IKernel property the SKContext - Phase 1 #2846

Merged
merged 13 commits into from
Sep 19, 2023
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,15 @@ public static async Task RunAsync()

var excuseFunction = kernel.CreateSemanticFunction(FunctionDefinition, maxTokens: 100, temperature: 0.4, topP: 1);

var result = await excuseFunction.InvokeAsync("I missed the F1 final race");
var result = await kernel.RunAsync("I missed the F1 final race", excuseFunction);
Console.WriteLine(result);

result = await excuseFunction.InvokeAsync("sorry I forgot your birthday");
result = await kernel.RunAsync("sorry I forgot your birthday", excuseFunction);
Console.WriteLine(result);

var fixedFunction = kernel.CreateSemanticFunction($"Translate this date {DateTimeOffset.Now:f} to French format", maxTokens: 100);

result = await fixedFunction.InvokeAsync();
result = await kernel.RunAsync(fixedFunction);
Console.WriteLine(result);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ private static async Task Example1Async(IKernel kernel, string searchSkillId)

// Run
var question = "What's the largest building in the world?";
var result = await kernel.Skills.GetFunction(searchSkillId, "search").InvokeAsync(question);
var function = kernel.Skills.GetFunction(searchSkillId, "search");
var result = await kernel.RunAsync(question, function);

Console.WriteLine(question);
Console.WriteLine($"----{searchSkillId}----");
Expand Down
60 changes: 30 additions & 30 deletions dotnet/samples/KernelSyntaxExamples/Example09_FunctionTypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ public static async Task RunAsync()
{
Console.WriteLine("======== Native function types ========");

var fakeContext = new SKContext(loggerFactory: ConsoleLogger.LoggerFactory);

var kernel = Kernel.Builder
.WithLoggerFactory(ConsoleLogger.LoggerFactory)
.WithOpenAIChatCompletionService(TestConfiguration.OpenAI.ChatModelId, TestConfiguration.OpenAI.ApiKey)
.Build();

var fakeContext = new SKContext(kernel, loggerFactory: ConsoleLogger.LoggerFactory);

// Load native skill into the kernel skill collection, sharing its functions with prompt templates
var test = kernel.ImportSkill(new LocalExampleSkill(), "test");

Expand Down Expand Up @@ -51,44 +51,45 @@ public static async Task RunAsync()
test["type18"]
);

await kernel.Skills.GetFunction("test", "type01").InvokeAsync();
await test["type01"].InvokeAsync();
// Using Kernel.RunAsync
await kernel.RunAsync(test["type01"]);
await kernel.RunAsync(kernel.Skills.GetFunction("test", "type01"));

await kernel.Skills.GetFunction("test", "type02").InvokeAsync();
await test["type02"].InvokeAsync();
await kernel.RunAsync(test["type02"]);
await kernel.RunAsync(kernel.Skills.GetFunction("test", "type02"));

await kernel.Skills.GetFunction("test", "type03").InvokeAsync();
await test["type03"].InvokeAsync();
await kernel.RunAsync(test["type03"]);
await kernel.RunAsync(kernel.Skills.GetFunction("test", "type03"));

await kernel.Skills.GetFunction("test", "type04").InvokeAsync(fakeContext);
await test["type04"].InvokeAsync(fakeContext);
await kernel.RunAsync(test["type04"], fakeContext.Variables);
await kernel.RunAsync(fakeContext.Variables, kernel.Skills.GetFunction("test", "type04"));

await kernel.Skills.GetFunction("test", "type05").InvokeAsync(fakeContext);
await test["type05"].InvokeAsync(fakeContext);
await kernel.RunAsync(test["type05"], fakeContext.Variables);
await kernel.RunAsync(fakeContext.Variables, kernel.Skills.GetFunction("test", "type05"));

await kernel.Skills.GetFunction("test", "type06").InvokeAsync(fakeContext);
await test["type06"].InvokeAsync(fakeContext);
await kernel.RunAsync(test["type06"], fakeContext.Variables);
await kernel.RunAsync(fakeContext.Variables, kernel.Skills.GetFunction("test", "type06"));

await kernel.Skills.GetFunction("test", "type07").InvokeAsync(fakeContext);
await test["type07"].InvokeAsync(fakeContext);
await kernel.RunAsync(test["type07"], fakeContext.Variables);
await kernel.RunAsync(fakeContext.Variables, kernel.Skills.GetFunction("test", "type07"));

await kernel.Skills.GetFunction("test", "type08").InvokeAsync("");
await test["type08"].InvokeAsync("");
await kernel.RunAsync("", test["type08"]);
await kernel.RunAsync("", kernel.Skills.GetFunction("test", "type08"));

await kernel.Skills.GetFunction("test", "type09").InvokeAsync("");
await test["type09"].InvokeAsync("");
await kernel.RunAsync("", test["type09"]);
await kernel.RunAsync("", kernel.Skills.GetFunction("test", "type09"));

await kernel.Skills.GetFunction("test", "type10").InvokeAsync("");
await test["type10"].InvokeAsync("");
await kernel.RunAsync("", test["type10"]);
await kernel.RunAsync("", kernel.Skills.GetFunction("test", "type10"));

await kernel.Skills.GetFunction("test", "type11").InvokeAsync("");
await test["type11"].InvokeAsync("");
await kernel.RunAsync("", test["type11"]);
await kernel.RunAsync("", kernel.Skills.GetFunction("test", "type11"));

await kernel.Skills.GetFunction("test", "type12").InvokeAsync(fakeContext);
await test["type12"].InvokeAsync(fakeContext);
await kernel.RunAsync(fakeContext.Variables, test["type12"]);
await kernel.RunAsync(fakeContext.Variables, kernel.Skills.GetFunction("test", "type12"));

await kernel.Skills.GetFunction("test", "type18").InvokeAsync();
await test["type18"].InvokeAsync();
await kernel.RunAsync(test["type18"]);
await kernel.RunAsync(kernel.Skills.GetFunction("test", "type18"));
}
}

Expand Down Expand Up @@ -132,8 +133,7 @@ public string Type05(SKContext context)
public async Task<string> Type06Async(SKContext context)
{
var summarizer = context.Skills.GetFunction("SummarizeSkill", "Summarize");

var summary = await summarizer.InvokeAsync("blah blah blah");
var summary = await context.Kernel.RunAsync("blah blah blah", summarizer);

Console.WriteLine($"Running function type 6 [{summary}]");
return "";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ private static async Task CustomTextCompletionWithSKFunctionAsync()

var textValidationFunction = kernel.CreateSemanticFunction(FunctionDefinition);

var result = await textValidationFunction.InvokeAsync("I mised the training session this morning");
var result = await textValidationFunction.InvokeAsync("I mised the training session this morning", kernel);
Console.WriteLine(result);

// Details of the my custom model response
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public static async Task RunAsync()
var func = kernel.CreateSemanticFunction(
"List the two planets closest to '{{$input}}', excluding moons, using bullet points.");

var result = await func.InvokeAsync("Jupiter");
var result = await func.InvokeAsync("Jupiter", kernel);
Console.WriteLine(result);

/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public static async Task RunAsync()
var plan = await planner.CreatePlanAsync(goal);

// Execute the full plan (which is a single function)
SKContext result = await plan.InvokeAsync();
SKContext result = await plan.InvokeAsync(kernel);

// Show the result, which should match the given goal
Console.WriteLine(result);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,15 +145,15 @@ private static IKernel InitializeKernel()
public class MarkupSkill
{
[SKFunction, Description("Run Markup")]
public async Task<string> RunMarkupAsync(string docString, SKContext context)
public async Task<string> RunMarkupAsync(string docString, SKContext context, IKernel kernel)
{
var plan = docString.FromMarkup("Run a piece of xml markup", context);

Console.WriteLine("Markup plan:");
Console.WriteLine(plan.ToPlanWithGoalString());
Console.WriteLine();

var result = await plan.InvokeAsync();
var result = await plan.InvokeAsync(kernel);
return result.Result;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public static async Task RunAsync()

// Using InvokeAsync with 3 results (Currently invoke only supports 1 result, but you can get the other results from the ModelResults)
var textResult = await myFunction.InvokeAsync("Sci-fi",
kernel,
settings: new CompleteRequestSettings { ResultsPerPrompt = 3, MaxTokens = 500, Temperature = 1, TopP = 0.5 });
Console.WriteLine(textResult);
Console.WriteLine(textResult.ModelResults.Select(result => result.GetOpenAIChatResult()).AsJson());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,22 +88,22 @@ public static async Task GroundednessCheckingSkill()
context.Variables.Set("topic", "people and places");
context.Variables.Set("example_entities", "John, Jane, mother, brother, Paris, Rome");

var extractionResult = (await entityExtraction.InvokeAsync(context)).Result;
var extractionResult = (await kernel.RunAsync(context.Variables, entityExtraction)).Result;

Console.WriteLine("======== Extract Entities ========");
Console.WriteLine(extractionResult);

context.Variables.Update(extractionResult);
context.Variables.Set("reference_context", s_groundingText);

var groundingResult = (await reference_check.InvokeAsync(context)).Result;
var groundingResult = (await kernel.RunAsync(context.Variables, reference_check)).Result;

Console.WriteLine("======== Reference Check ========");
Console.WriteLine(groundingResult);

context.Variables.Update(summaryText);
context.Variables.Set("ungrounded_entities", groundingResult);
var excisionResult = await entity_excision.InvokeAsync(context);
var excisionResult = await kernel.RunAsync(context.Variables, entity_excision);

Console.WriteLine("======== Excise Entities ========");
Console.WriteLine(excisionResult.Result);
Expand Down Expand Up @@ -141,7 +141,7 @@ public static async Task PlanningWithGroundedness()
var plan = await planner.CreatePlanAsync(ask);
Console.WriteLine(plan.ToPlanWithGoalString());

var results = await plan.InvokeAsync(s_groundingText);
var results = await kernel.RunAsync(s_groundingText, plan);
Console.WriteLine(results.Result);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ private static async Task RunWithQuestion(IKernel kernel, ExecutionResult curren
StepwisePlanner planner = new(kernel: kernel, config: plannerConfig);
var plan = planner.CreatePlan(question);

result = await plan.InvokeAsync(kernel.CreateNewContext());
result = await kernel.RunAsync(plan);

if (result.Result.Contains("Result not found, review _stepsTaken to see what", StringComparison.OrdinalIgnoreCase))
{
Expand Down
6 changes: 4 additions & 2 deletions dotnet/samples/NCalcSkills/LanguageCalculatorSkill.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ namespace NCalcSkills;
public class LanguageCalculatorSkill
{
private readonly ISKFunction _mathTranslator;

private readonly IKernel _kernel;
private const string MathTranslatorPrompt =
@"Translate a math problem into a expression that can be executed using .net NCalc library. Use the output of running this code to answer the question.
Available functions: Abs, Acos, Asin, Atan, Ceiling, Cos, Exp, Floor, IEEERemainder, Log, Log10, Max, Min, Pow, Round, Sign, Sin, Sqrt, Tan, and Truncate. in and if are also supported.
Expand Down Expand Up @@ -75,6 +75,8 @@ public LanguageCalculatorSkill(IKernel kernel)
maxTokens: 256,
temperature: 0.0,
topP: 1);

this._kernel = kernel;
RogerBarreto marked this conversation as resolved.
Show resolved Hide resolved
}

/// <summary>
Expand All @@ -93,7 +95,7 @@ public LanguageCalculatorSkill(IKernel kernel)

try
{
answer = await this._mathTranslator.InvokeAsync(input).ConfigureAwait(false);
answer = await this._mathTranslator.InvokeAsync(input, this._kernel).ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,13 +151,15 @@ private Mock<IKernel> CreateMockKernelAndFunctionFlowWithTestString(string testP
skills.Setup(x => x.GetFunctionsView(It.IsAny<bool>(), It.IsAny<bool>())).Returns(functionsView);
}

var returnContext = new SKContext(
var returnContext = new SKContext(kernel.Object,
new ContextVariables(testPlanString),
skills.Object
);

var context = new SKContext(
skills: skills.Object
kernel.Object,
skills: skills.Object,
loggerFactory: kernel.Object.LoggerFactory
);

var mockFunctionFlowFunction = new Mock<ISKFunction>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Orchestration;
using Microsoft.SemanticKernel.Planning.Sequential;
Expand All @@ -20,6 +21,7 @@ public class SKContextExtensionsTests
public async Task CanCallGetAvailableFunctionsWithNoFunctionsAsync()
{
// Arrange
var kernel = new Mock<IKernel>();
var variables = new ContextVariables();
var skills = new SkillCollection();
var loggerFactory = TestConsoleLogger.LoggerFactory;
Expand All @@ -43,7 +45,7 @@ public async Task CanCallGetAvailableFunctionsWithNoFunctionsAsync()
.Returns(asyncEnumerable);

// Arrange GetAvailableFunctionsAsync parameters
var context = new SKContext(variables, skills, loggerFactory);
var context = new SKContext(kernel.Object, variables, skills, loggerFactory);
var config = new SequentialPlannerConfig() { Memory = memory.Object };
var semanticQuery = "test";

Expand All @@ -61,6 +63,7 @@ public async Task CanCallGetAvailableFunctionsWithNoFunctionsAsync()
public async Task CanCallGetAvailableFunctionsWithFunctionsAsync()
{
// Arrange
var kernel = new Mock<IKernel>();
var variables = new ContextVariables();
var loggerFactory = TestConsoleLogger.LoggerFactory;
var cancellationToken = default(CancellationToken);
Expand Down Expand Up @@ -97,7 +100,7 @@ public async Task CanCallGetAvailableFunctionsWithFunctionsAsync()
skills.Setup(x => x.GetFunctionsView(It.IsAny<bool>(), It.IsAny<bool>())).Returns(functionsView);

// Arrange GetAvailableFunctionsAsync parameters
var context = new SKContext(variables, skills.Object, loggerFactory);
var context = new SKContext(kernel.Object, variables, skills.Object, loggerFactory);
var config = new SequentialPlannerConfig() { Memory = memory.Object };
var semanticQuery = "test";

Expand Down Expand Up @@ -126,6 +129,7 @@ public async Task CanCallGetAvailableFunctionsWithFunctionsAsync()
public async Task CanCallGetAvailableFunctionsWithFunctionsWithRelevancyAsync()
{
// Arrange
var kernel = new Mock<IKernel>();
var variables = new ContextVariables();
var loggerFactory = TestConsoleLogger.LoggerFactory;
var cancellationToken = default(CancellationToken);
Expand Down Expand Up @@ -162,7 +166,7 @@ public async Task CanCallGetAvailableFunctionsWithFunctionsWithRelevancyAsync()
skills.Setup(x => x.GetFunctionsView(It.IsAny<bool>(), It.IsAny<bool>())).Returns(functionsView);

// Arrange GetAvailableFunctionsAsync parameters
var context = new SKContext(variables, skills.Object, loggerFactory);
var context = new SKContext(kernel.Object, variables, skills.Object, loggerFactory);
var config = new SequentialPlannerConfig { RelevancyThreshold = 0.78, Memory = memory.Object };
var semanticQuery = "test";

Expand Down Expand Up @@ -191,6 +195,7 @@ public async Task CanCallGetAvailableFunctionsWithFunctionsWithRelevancyAsync()
public async Task CanCallGetAvailableFunctionsAsyncWithDefaultRelevancyAsync()
{
// Arrange
var kernel = new Mock<IKernel>();
var variables = new ContextVariables();
var skills = new SkillCollection();
var loggerFactory = TestConsoleLogger.LoggerFactory;
Expand All @@ -215,7 +220,7 @@ public async Task CanCallGetAvailableFunctionsAsyncWithDefaultRelevancyAsync()
.Returns(asyncEnumerable);

// Arrange GetAvailableFunctionsAsync parameters
var context = new SKContext(variables, skills, loggerFactory);
var context = new SKContext(kernel.Object, variables, skills, loggerFactory);
var config = new SequentialPlannerConfig { RelevancyThreshold = 0.78, Memory = memory.Object };
var semanticQuery = "test";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public SequentialPlanParserTests(ITestOutputHelper testOutputHelper)
IKernel kernel,
ContextVariables? variables = null)
{
return new SKContext(variables, kernel.Skills, kernel.LoggerFactory);
return new SKContext(kernel, variables, kernel.Skills, kernel.LoggerFactory);
}

private static Mock<ISKFunction> CreateMockFunction(FunctionView functionView, string result = "")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,14 @@ public async Task ItCanCreatePlanAsync(string goal)
var expectedSkills = input.Select(x => x.skillName).ToList();

var context = new SKContext(
kernel.Object,
new ContextVariables(),
skills.Object,
new Mock<ILoggerFactory>().Object
);

var returnContext = new SKContext(
kernel.Object,
new ContextVariables(),
skills.Object,
new Mock<ILoggerFactory>().Object
Expand Down Expand Up @@ -155,12 +157,14 @@ public async Task InvalidXMLThrowsAsync()

var planString = "<plan>notvalid<</plan>";
var returnContext = new SKContext(
kernel.Object,
new ContextVariables(planString),
skills.Object,
new Mock<ILoggerFactory>().Object
);

var context = new SKContext(
kernel.Object,
new ContextVariables(),
skills.Object,
new Mock<ILoggerFactory>().Object
Expand Down