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] Add KernelPluginMiddleware in AutoGen.SemanticKernel #2595

Merged
merged 6 commits into from
May 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions dotnet/AutoGen.sln
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoGen.Core", "src\AutoGen
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoGen.OpenAI", "src\AutoGen.OpenAI\AutoGen.OpenAI.csproj", "{63445BB7-DBB9-4AEF-9D6F-98BBE75EE1EC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoGen.Mistral", "src\AutoGen.Mistral\AutoGen.Mistral.csproj", "{6585D1A4-3D97-4D76-A688-1933B61AEB19}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoGen.Mistral", "src\AutoGen.Mistral\AutoGen.Mistral.csproj", "{6585D1A4-3D97-4D76-A688-1933B61AEB19}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoGen.Mistral.Tests", "test\AutoGen.Mistral.Tests\AutoGen.Mistral.Tests.csproj", "{15441693-3659-4868-B6C1-B106F52FF3BA}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoGen.Mistral.Tests", "test\AutoGen.Mistral.Tests\AutoGen.Mistral.Tests.csproj", "{15441693-3659-4868-B6C1-B106F52FF3BA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoGen.SemanticKernel.Tests", "test\AutoGen.SemanticKernel.Tests\AutoGen.SemanticKernel.Tests.csproj", "{1DFABC4A-8458-4875-8DCB-59F3802DAC65}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down Expand Up @@ -87,6 +89,10 @@ Global
{15441693-3659-4868-B6C1-B106F52FF3BA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{15441693-3659-4868-B6C1-B106F52FF3BA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{15441693-3659-4868-B6C1-B106F52FF3BA}.Release|Any CPU.Build.0 = Release|Any CPU
{1DFABC4A-8458-4875-8DCB-59F3802DAC65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1DFABC4A-8458-4875-8DCB-59F3802DAC65}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1DFABC4A-8458-4875-8DCB-59F3802DAC65}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1DFABC4A-8458-4875-8DCB-59F3802DAC65}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -104,6 +110,7 @@ Global
{63445BB7-DBB9-4AEF-9D6F-98BBE75EE1EC} = {18BF8DD7-0585-48BF-8F97-AD333080CE06}
{6585D1A4-3D97-4D76-A688-1933B61AEB19} = {18BF8DD7-0585-48BF-8F97-AD333080CE06}
{15441693-3659-4868-B6C1-B106F52FF3BA} = {F823671B-3ECA-4AE6-86DA-25E920D3FE64}
{1DFABC4A-8458-4875-8DCB-59F3802DAC65} = {F823671B-3ECA-4AE6-86DA-25E920D3FE64}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {93384647-528D-46C8-922C-8DB36A382F0B}
Expand Down
2 changes: 1 addition & 1 deletion dotnet/eng/MetaInfo.props
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VersionPrefix>0.0.12</VersionPrefix>
<VersionPrefix>0.0.13</VersionPrefix>
<Authors>AutoGen</Authors>
<PackageProjectUrl>https://microsoft.github.io/autogen-for-net/</PackageProjectUrl>
<RepositoryUrl>https://github.com/microsoft/autogen</RepositoryUrl>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// MiddlewareAgentCodeSnippet.cs

using AutoGen.Core;
using System.Text.Json;
using AutoGen.Core;
using AutoGen.OpenAI;
using FluentAssertions;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
// MistralAICodeSnippet.cs

#region using_statement
using AutoGen.Mistral;
using AutoGen.Core;
using AutoGen.Mistral;
using AutoGen.Mistral.Extension;
using FluentAssertions;
#endregion using_statement
Expand Down Expand Up @@ -83,4 +83,4 @@ public async Task MistralAIChatAgentGetWeatherToolUsageAsync()
reply.GetContent().Should().Be("The weather in Seattle is sunny.");
#endregion send_message_with_function_call
}
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Example01_AssistantAgent.cs

using AutoGen.Core;
using AutoGen;
using AutoGen.BasicSample;
using AutoGen.Core;
using FluentAssertions;

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Example02_TwoAgent_MathChat.cs

using AutoGen.Core;
using AutoGen;
using AutoGen.BasicSample;
using AutoGen.Core;
using FluentAssertions;
public static class Example02_TwoAgent_MathChat
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
// Example03_Agent_FunctionCall.cs

using AutoGen;
using AutoGen.Core;
using AutoGen.BasicSample;
using AutoGen.Core;
using FluentAssertions;

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
// Example04_Dynamic_GroupChat_Coding_Task.cs

using AutoGen;
using AutoGen.Core;
using AutoGen.BasicSample;
using AutoGen.Core;
using AutoGen.DotnetInteractive;
using AutoGen.OpenAI;
using FluentAssertions;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
using System.Text.Json;
using AutoGen;
using AutoGen.BasicSample;
using AutoGen.DotnetInteractive;
using AutoGen.Core;
using AutoGen.DotnetInteractive;
using AutoGen.OpenAI;
using FluentAssertions;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,4 @@ public static async Task RunAsync()
tokenCounterMiddleware.GetCompletionTokenCount().Should().BeGreaterThan(0);
#endregion chat_with_agent
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Example15_ImageMessage.cs
// Example15_GPT4V_BinaryDataImageMessage.cs

using AutoGen.Core;
using AutoGen.OpenAI;
Expand Down
2 changes: 1 addition & 1 deletion dotnet/src/AutoGen.Mistral/DTOs/ChatCompletionResponse.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation. All rights reserved.
// ChatCompletionResponse.cs

using System.Collections.Generic;
Expand Down
2 changes: 1 addition & 1 deletion dotnet/src/AutoGen.Mistral/DTOs/Error.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Error.cs

using System.Text.Json.Serialization;
Expand Down
2 changes: 1 addition & 1 deletion dotnet/src/AutoGen.Mistral/DTOs/Model.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Model.cs

using System;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<RootNamespace>AutoGen.SemanticKernel</RootNamespace>
</PropertyGroup>

<PropertyGroup>
<NoWarn>$(NoWarn);SKEXP0110</NoWarn>
</PropertyGroup>

Expand Down
34 changes: 34 additions & 0 deletions dotnet/src/AutoGen.SemanticKernel/Extension/KernelExtension.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// KernelExtension.cs

using System.Linq;
using Microsoft.SemanticKernel;

namespace AutoGen.SemanticKernel.Extension;
Expand All @@ -11,4 +12,37 @@ public static SemanticKernelAgent ToSemanticKernelAgent(this Kernel kernel, stri
{
return new SemanticKernelAgent(kernel, name, systemMessage, settings);
}

/// <summary>
/// Convert a <see cref="KernelFunctionMetadata"/> to a <see cref="FunctionContract"/>
/// </summary>
/// <param name="metadata">kernel function metadata</param>
public static FunctionContract ToFunctionContract(this KernelFunctionMetadata metadata)
{
return new FunctionContract()
{
Name = metadata.Name,
Description = metadata.Description,
Parameters = metadata.Parameters.Select(p => p.ToFunctionParameterContract()).ToList(),
ReturnType = metadata.ReturnParameter.ParameterType,
ReturnDescription = metadata.ReturnParameter.Description,
ClassName = metadata.PluginName,
};
}

/// <summary>
/// Convert a <see cref="KernelParameterMetadata"/> to a <see cref="FunctionParameterContract"/>
/// </summary>
/// <param name="metadata">kernel parameter metadata</param>
public static FunctionParameterContract ToFunctionParameterContract(this KernelParameterMetadata metadata)
{
return new FunctionParameterContract()
{
Name = metadata.Name,
Description = metadata.Description,
DefaultValue = metadata.DefaultValue,
IsRequired = metadata.IsRequired,
ParameterType = metadata.ParameterType,
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// KernelPluginMiddleware.cs

using System;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;
using AutoGen.SemanticKernel.Extension;
using Microsoft.SemanticKernel;

namespace AutoGen.SemanticKernel;

/// <summary>
/// A middleware that consumes <see cref="KernelPlugin"/>
/// </summary>
public class KernelPluginMiddleware : IMiddleware
{
private readonly KernelPlugin _kernelPlugin;
private readonly FunctionCallMiddleware _functionCallMiddleware;
public string? Name => nameof(KernelPluginMiddleware);

public KernelPluginMiddleware(Kernel kernel, KernelPlugin kernelPlugin)
{
_kernelPlugin = kernelPlugin;
var functionContracts = kernelPlugin.Select(k => k.Metadata.ToFunctionContract());
var functionMap = kernelPlugin.ToDictionary(kv => kv.Metadata.Name, kv => InvokeFunctionPartial(kernel, kv));
_functionCallMiddleware = new FunctionCallMiddleware(functionContracts, functionMap, Name);
}

public Task<IMessage> InvokeAsync(MiddlewareContext context, IAgent agent, CancellationToken cancellationToken = default)
{
return _functionCallMiddleware.InvokeAsync(context, agent, cancellationToken);
}

private async Task<string> InvokeFunctionAsync(Kernel kernel, KernelFunction function, string arguments)
{
var kernelArguments = new KernelArguments();
var parameters = function.Metadata.Parameters;
var jsonObject = JsonSerializer.Deserialize<JsonObject>(arguments) ?? new JsonObject();
foreach (var parameter in parameters)
{
var parameterName = parameter.Name;
if (jsonObject.ContainsKey(parameterName))
{
var parameterType = parameter.ParameterType ?? throw new ArgumentException($"Missing parameter type for {parameterName}");
var parameterValue = jsonObject[parameterName];
var parameterObject = parameterValue.Deserialize(parameterType);
kernelArguments.Add(parameterName, parameterObject);
}
else
{
if (parameter.DefaultValue != null)
{
kernelArguments.Add(parameterName, parameter.DefaultValue);
}
else if (parameter.IsRequired)
{
throw new ArgumentException($"Missing required parameter: {parameterName}");
}
}
}
var result = await function.InvokeAsync(kernel, kernelArguments);
LittleLittleCloud marked this conversation as resolved.
Show resolved Hide resolved

return result.ToString();
}

private Func<string, Task<string>> InvokeFunctionPartial(Kernel kernel, KernelFunction function)
{
return async (string args) =>
{
var result = await InvokeFunctionAsync(kernel, function, args);
return result.ToString();
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public async Task MistralAgentFunctionCallMessageTest()
new TextMessage(Role.User, "what's the weather in Seattle?"),
new ToolCallMessage(this.GetWeatherFunctionContract.Name!, weatherFunctionArgumets, from: agent.Name),
new ToolCallResultMessage(functionCallResult, this.GetWeatherFunctionContract.Name!, weatherFunctionArgumets),
];
];

var reply = await agent.SendAsync(chatHistory: chatHistory);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[
{
"Name": "_ItCreateFunctionContractsFromMethod_b__2_0",
"Description": "",
"Parameters": [],
"ReturnType": "System.String, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"ReturnDescription": ""
},
{
"Name": "_ItCreateFunctionContractsFromMethod_b__2_1",
"Description": "",
"Parameters": [
{
"Name": "message",
"Description": "",
"ParameterType": "System.String, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"IsRequired": true,
"DefaultValue": ""
}
],
"ReturnType": "System.String, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"ReturnDescription": ""
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[
{
"Name": "sayHello",
"Description": "Generic function, unknown purpose",
"Parameters": [],
"ReturnDescription": ""
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[
{
"ClassName": "test_plugin",
"Name": "GetState",
"Description": "Gets the state of the light.",
"Parameters": [],
"ReturnType": "System.String, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"ReturnDescription": ""
},
{
"ClassName": "test_plugin",
"Name": "ChangeState",
"Description": "Changes the state of the light.'",
"Parameters": [
{
"Name": "newState",
"Description": "new state",
"ParameterType": "System.Boolean, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"IsRequired": true,
"DefaultValue": ""
}
],
"ReturnType": "System.String, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"ReturnDescription": ""
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>$(TestTargetFramework)</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<NoWarn>$(NoWarn);SKEXP0110</NoWarn>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="ApprovalTests" Version="$(ApprovalTestVersion)" />
<PackageReference Include="FluentAssertions" Version="$(FluentAssertionVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftNETTestSdkVersion)" />
<PackageReference Include="xunit" Version="$(XUnitVersion)" />
<PackageReference Include="xunit.runner.console" Version="$(XUnitVersion)" />
<PackageReference Include="xunit.runner.visualstudio" Version="$(XUnitVersion)" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\AutoGen.SemanticKernel\AutoGen.SemanticKernel.csproj" />
<ProjectReference Include="..\..\src\AutoGen.SourceGenerator\AutoGen.SourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\..\src\AutoGen\AutoGen.csproj" />
<ProjectReference Include="..\AutoGen.Tests\AutoGen.Tests.csproj" />
</ItemGroup>

</Project>
Loading
Loading