Skip to content

Commit

Permalink
Update planner article
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewbolanos committed Dec 13, 2023
1 parent 55aa203 commit dc7d820
Show file tree
Hide file tree
Showing 8 changed files with 270 additions and 431 deletions.
5 changes: 3 additions & 2 deletions samples/dotnet/11-Planner/11-Planner.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<UserSecretsId>5ee045b0-aea3-4f08-8d31-32d1a6f8fed0</UserSecretsId>
<NoWarn>SKEXP0003, SKEXP0004, SKEXP0011, SKEXP0052, SKEXP0060</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand All @@ -17,8 +18,8 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SemanticKernel" />
<PackageReference Include="Microsoft.SemanticKernel.Planners.Core" />
<ProjectReference Include="/Users/matthewbolanos/semantic-kernel/dotnet/src/SemanticKernel.MetaPackage/SemanticKernel.MetaPackage.csproj" />
<ProjectReference Include="/Users/matthewbolanos/semantic-kernel/dotnet/src/Planners/Planners.Handlebars/Planners.Handlebars.csproj" />
</ItemGroup>

<ItemGroup>
Expand Down
25 changes: 25 additions & 0 deletions samples/dotnet/11-Planner/11-Planner.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.002.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "11-Planner", "11-Planner.csproj", "{FD18937D-8AA6-4EEC-926D-C288FF848F63}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FD18937D-8AA6-4EEC-926D-C288FF848F63}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FD18937D-8AA6-4EEC-926D-C288FF848F63}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FD18937D-8AA6-4EEC-926D-C288FF848F63}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FD18937D-8AA6-4EEC-926D-C288FF848F63}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C6F0D9F7-FAC3-4F32-A7C1-3632F9CCAE5A}
EndGlobalSection
EndGlobal
74 changes: 52 additions & 22 deletions samples/dotnet/11-Planner/Program.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
// Copyright (c) Microsoft. All rights reserved.

using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Planners;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Plugins;

using ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
{
Expand All @@ -13,29 +15,57 @@
});

// Create kernel
IKernel kernel = new KernelBuilder()
// Add a text or chat completion service using either:
// .WithAzureTextCompletionService()
// .WithAzureChatCompletionService()
// .WithOpenAITextCompletionService()
// .WithOpenAIChatCompletionService()
.WithCompletionService()
.WithLoggerFactory(loggerFactory)
.Build();
var builder = Kernel.CreateBuilder();
// Add a text or chat completion service using either:
// builder.Services.AddAzureOpenAIChatCompletion()
// builder.Services.AddAzureOpenAITextGeneration()
// builder.Services.AddOpenAIChatCompletion()
// builder.Services.AddOpenAITextGeneration()
builder.WithCompletionService();
builder.Services.AddLogging(c => c.AddDebug().SetMinimumLevel(LogLevel.Trace));
builder.Plugins.AddFromType<MathSolver>();
var kernel = builder.Build();

// Add the math plugin
var mathPlugin = kernel.ImportFunctions(new Plugins.MathPlugin.Math(), "MathPlugin");
// Create chat history
ChatHistory history = [];

// Create a planner
var planner = new SequentialPlanner(kernel);
// Get chat completion service
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();

var ask = "If my investment of 2130.23 dollars increased by 23%, how much would I have after I spent $5 on a latte?";
var plan = await planner.CreatePlanAsync(ask);
// Start the conversation
while (true)
{
// Get user input
Console.Write("User > ");
history.AddUserMessage(Console.ReadLine()!);

// Enable auto function calling
OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new()
{
ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
};

Console.WriteLine("Plan:\n");
Console.WriteLine(JsonSerializer.Serialize(plan, new JsonSerializerOptions { WriteIndented = true }));
// Get the response from the AI
var result = chatCompletionService.GetStreamingChatMessageContentsAsync(
history,
executionSettings: openAIPromptExecutionSettings,
kernel: kernel);

var result = await kernel.RunAsync(plan);
// Stream the results
string fullMessage = "";
var first = true;
await foreach (var content in result)
{
if (content.Role.HasValue && first)
{
Console.Write("Assistant > ");
first = false;
}
Console.Write(content.Content);
fullMessage += content.Content;
}
Console.WriteLine();

Console.WriteLine("Plan results:");
Console.WriteLine(result.GetValue<string>()!.Trim());
// Add the message from the agent to the chat history
history.AddAssistantMessage(fullMessage);
}
53 changes: 53 additions & 0 deletions samples/dotnet/11-Planner/plugins/MathPlugin.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright (c) Microsoft. All rights reserved.

using System.ComponentModel;
using Microsoft.SemanticKernel;

namespace Plugins;

public class MathPlugin
{
[KernelFunction, Description("Take the square root of a number")]
public static double Sqrt(
[Description("The number to take a square root of")] double number1
)
{
return Math.Sqrt(number1);
}

[KernelFunction, Description("Add two numbers")]
public static double Add(
[Description("The first number to add")] double number1,
[Description("The second number to add")] double number2
)
{
return number1 + number2;
}

[KernelFunction, Description("Subtract two numbers")]
public static double Subtract(
[Description("The first number to subtract from")] double number1,
[Description("The second number to subtract away")] double number2
)
{
return number1 - number2;
}

[KernelFunction, Description("Multiply two numbers. When increasing by a percentage, don't forget to add 1 to the percentage.")]
public static double Multiply(
[Description("The first number to multiply")] double number1,
[Description("The second number to multiply")] double number2
)
{
return number1 * number2;
}

[KernelFunction, Description("Divide two numbers")]
public static double Divide(
[Description("The first number to divide from")] double number1,
[Description("The second number to divide by")] double number2
)
{
return number1 / number2;
}
}
51 changes: 0 additions & 51 deletions samples/dotnet/11-Planner/plugins/MathPlugin/MathPlugin.cs

This file was deleted.

43 changes: 43 additions & 0 deletions samples/dotnet/11-Planner/plugins/MathSolver.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright (c) Microsoft. All rights reserved.

using System.ComponentModel;
using Json.More;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Planning.Handlebars;

namespace Plugins;

public class MathSolver
{
private readonly ILogger _logger;

public MathSolver(ILoggerFactory loggerFactory)
{
this._logger = loggerFactory.CreateLogger<MathSolver>();
}

[KernelFunction]
[Description("Solves a math problem.")]
[return: Description("The solution to the math problem.")]
public async Task<string> SolveAsync(
Kernel kernel,
[Description("The math problem to solve; describe it in 2-3 sentences to ensure full context is provided")] string problem
)
{
var kernelWithMath = kernel.Clone();
kernelWithMath.Plugins.AddFromType<MathPlugin>();

var planner = new HandlebarsPlanner(new HandlebarsPlannerOptions() { AllowLoops = true });

// Create a plan
var plan = await planner.CreatePlanAsync(kernelWithMath, problem);
this._logger.LogInformation($"Plan: {plan}");

// Execute the plan
var result = (await plan.InvokeAsync(kernelWithMath, [])).Trim();
this._logger.LogInformation($"Results: {result}");

return result;
}
}
22 changes: 11 additions & 11 deletions samples/python/11-Planner/main.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
import semantic_kernel as sk
from plugins.MathPlugin.Math import Math
from semantic_kernel.planning.basic_planner import BasicPlanner
import config.add_completion_service


async def main():
import semantic_kernel as sk
from plugins.MathPlugin.Math import Math
from semantic_kernel.planning.sequential_planner import SequentialPlanner
import config.add_completion_service

# Initialize the kernel
kernel = sk.Kernel()
# Add a text or chat completion service using either:
# kernel.add_text_completion_service()
# kernel.add_chat_service()
kernel.add_completion_service()

planner = BasicPlanner()

# Import the native functions
math_plugin = kernel.import_skill(Math(), "MathPlugin")

planner = SequentialPlanner(kernel)

ask = "If my investment of 2130.23 dollars increased by 23%, how much would I have after I spent $5 on a latte?"
plan = await planner.create_plan_async(ask, kernel)

# Execute the plan
result = await planner.execute_plan_async(plan, kernel)
# Create a plan
plan = await planner.create_plan_async(ask)

# Execute the plan
result = await plan.invoke_async()
print("Plan results:")
print(result)

Expand Down
Loading

0 comments on commit dc7d820

Please sign in to comment.