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

gRPC skills functionality #814

Merged
merged 10 commits into from
May 8, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 4 additions & 6 deletions dotnet/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,22 @@
<PackageVersion Include="System.Linq.Async" Version="[6.0.1, )" />
<PackageVersion Include="System.Text.Json" Version="[6.0.0, )" />
<PackageVersion Include="Azure.AI.OpenAI" Version="[1.0.0-beta.5, )" />

<!-- Microsoft.Extensions.Logging -->
<PackageVersion Include="Microsoft.Extensions.Logging" Version="[6.0.0, )" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="[6.0.0, )" />
<PackageVersion Include="Microsoft.Extensions.Logging.Console" Version="[6.0.0, )" />

<!-- Microsoft.Extensions.Configuration -->
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.4" />
<PackageVersion Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.UserSecrets" Version="7.0.0" />

<!-- Test -->
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageVersion Include="Moq" Version="4.18.4" />
<PackageVersion Include="xunit" Version="2.4.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.4.5" />
<PackageVersion Include="coverlet.collector" Version="3.2.0" />

<!-- Skills -->
<PackageVersion Include="DocumentFormat.OpenXml" Version="2.20.0" />
<PackageVersion Include="Microsoft.Data.Sqlite" Version="[7.0, )" />
Expand All @@ -38,8 +34,10 @@
<PackageVersion Include="Microsoft.Identity.Client.Extensions.Msal" Version="[2.28.0, )" />
<PackageVersion Include="Microsoft.OpenApi" Version="[1.6.3, )" />
<PackageVersion Include="Microsoft.OpenApi.Readers" Version="[1.6.3, )" />
<PackageVersion Include="Newtonsoft.Json" Version="[13.0.3, )" />

<PackageVersion Include="Newtonsoft.Json" Version="[11.0.1, )" />
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️

<PackageVersion Include="Grpc.Net.Client" Version="2.52.0" />
<PackageVersion Include="protobuf-net" Version="3.2.16" />
<PackageVersion Include="protobuf-net.Reflection" Version="3.2.12" />
<!-- Symbols -->
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="1.1.1" />

Expand Down
8 changes: 7 additions & 1 deletion dotnet/SK-dotnet.sln
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Planning.SequentialPlanner"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Connectors.Memory.AzureCognitiveSearch", "src\Connectors\Connectors.Memory.AzureCognitiveSearch\Connectors.Memory.AzureCognitiveSearch.csproj", "{EC3BB6D1-2FB2-4702-84C6-F791DE533ED4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Skills.Grpc", "src\Skills\Skills.Grpc\Skills.Grpc.csproj", "{E52F805C-794A-4CA9-B684-DFF358B18820}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -203,6 +205,10 @@ Global
{EC3BB6D1-2FB2-4702-84C6-F791DE533ED4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EC3BB6D1-2FB2-4702-84C6-F791DE533ED4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EC3BB6D1-2FB2-4702-84C6-F791DE533ED4}.Release|Any CPU.Build.0 = Release|Any CPU
{E52F805C-794A-4CA9-B684-DFF358B18820}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E52F805C-794A-4CA9-B684-DFF358B18820}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E52F805C-794A-4CA9-B684-DFF358B18820}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E52F805C-794A-4CA9-B684-DFF358B18820}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -213,7 +219,6 @@ Global
{47C6F821-5103-431F-B3B8-A2868A68BB78} = {FA3720F1-C99A-49B2-9577-A940257098BF}
{3EB61E99-C39B-4620-9482-F8DA18E48525} = {FA3720F1-C99A-49B2-9577-A940257098BF}
{34A7F1EF-D243-4160-A413-D713FEABCD94} = {FA3720F1-C99A-49B2-9577-A940257098BF}
{E4B777A1-28E1-41BE-96AE-7F3EC61FD5D4} = {831DDCA2-7D2C-4C31-80DB-6BDB3E1F7AE0}
{F94D1938-9DB7-4B24-9FF3-166DDFD96330} = {9ECD1AA0-75B3-4E25-B0B5-9F0945B64974}
{689A5041-BAE7-448F-9BDC-4672E96249AA} = {9ECD1AA0-75B3-4E25-B0B5-9F0945B64974}
{EEA87FBC-4ED5-458C-ABD3-BEAEEB535BAF} = {9ECD1AA0-75B3-4E25-B0B5-9F0945B64974}
Expand All @@ -240,6 +245,7 @@ Global
{F51017A9-15C8-472D-893C-080046D710A6} = {078F96B4-09E1-4E0E-B214-F71A4F4BF633}
{A350933D-F9D5-4AD3-8C4F-B856B5020297} = {078F96B4-09E1-4E0E-B214-F71A4F4BF633}
{EC3BB6D1-2FB2-4702-84C6-F791DE533ED4} = {0247C2C9-86C3-45BA-8873-28B0948EDC0C}
{E52F805C-794A-4CA9-B684-DFF358B18820} = {9ECD1AA0-75B3-4E25-B0B5-9F0945B64974}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {FBDC56A3-86AD-4323-AA0F-201E59123B83}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Planning.SequentialPlanner" PublicKey="$(StrongNamePublicKey)"/>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Skills.OpenAPI" PublicKey="$(StrongNamePublicKey)"/>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Connectors.Memory.CosmosDB" PublicKey="$(StrongNamePublicKey)"/>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Skills.Grpc" PublicKey="$(StrongNamePublicKey)"/>
<InternalsVisibleTo Include="SemanticKernel.Skills.UnitTests" PublicKey="$(StrongNamePublicKey)"/>
<InternalsVisibleTo Include="SemanticKernel.UnitTests" PublicKey="$(StrongNamePublicKey)"/>
<InternalsVisibleTo Include="IntegrationTests" PublicKey="$(StrongNamePublicKey)"/>
Expand Down
11 changes: 7 additions & 4 deletions dotnet/src/SemanticKernel/SemanticKernel.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,25 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>

<Import Project="$(RepoRoot)/dotnet/nuget/nuget-package.props" />

<PropertyGroup>
<!-- NuGet Package Settings -->
<Title>Semantic Kernel Core</Title>
<Description>Semantic Kernel core orchestration, runtime and skills.
This package is automatically installed by 'Microsoft.SemanticKernel' package with other useful packages.
Install this package manually only if you are selecting individual Semantic Kernel components.</Description>
<Description>
Semantic Kernel core orchestration, runtime and skills.
This package is automatically installed by 'Microsoft.SemanticKernel' package with other useful packages.
Install this package manually only if you are selecting individual Semantic Kernel components.
</Description>
</PropertyGroup>

<ItemGroup>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Planning.ActionPlanner" PublicKey="$(StrongNamePublicKey)"/>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Planning.SequentialPlanner" PublicKey="$(StrongNamePublicKey)"/>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Connectors.AI.OpenAI" PublicKey="$(StrongNamePublicKey)"/>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Skills.OpenAPI" PublicKey="$(StrongNamePublicKey)"/>
<InternalsVisibleTo Include="Microsoft.SemanticKernel.Skills.Grpc" PublicKey="$(StrongNamePublicKey)"/>
<InternalsVisibleTo Include="SemanticKernel.UnitTests" PublicKey="$(StrongNamePublicKey)"/>
<InternalsVisibleTo Include="SemanticKernel.Skills.UnitTests" PublicKey="$(StrongNamePublicKey)"/>
<InternalsVisibleTo Include="SemanticKernel.IntegrationTests" PublicKey="$(StrongNamePublicKey)"/>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright (c) Microsoft. All rights reserved.

using System.Collections.Generic;
using Microsoft.SemanticKernel.SkillDefinition;
using Microsoft.SemanticKernel.Skills.Grpc.Model;

// ReSharper disable once CheckNamespace
namespace Microsoft.SemanticKernel.Skills.Grpc.Extensions;

/// <summary>
/// Class for extensions methods for the <see cref="GrpcOperation"/> class.
/// </summary>
internal static class GrpcOperationExtensions
{
/// <summary>
/// Returns list of gRPC operation parameters.
/// </summary>
/// <returns>The list of parameters.</returns>
public static IReadOnlyList<ParameterView> GetParameters(this GrpcOperation operation)
SergeyMenshykh marked this conversation as resolved.
Show resolved Hide resolved
{
var parameters = new List<ParameterView>();

//Register the "address" parameter so that it's possible to override it if needed.
parameters.Add(new ParameterView(GrpcOperation.AddressArgumentName, "Address for gRPC channel to use.", string.Empty));

//Register the "payload" parameter to be used as gRPC operation request message.
parameters.Add(new ParameterView(GrpcOperation.PayloadArgumentName, "gRPC request message.", string.Empty));

return parameters;
}
}
191 changes: 191 additions & 0 deletions dotnet/src/Skills/Skills.Grpc/Extensions/KernelGrpcExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
// Copyright (c) Microsoft. All rights reserved.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel.Diagnostics;
using Microsoft.SemanticKernel.Orchestration;
using Microsoft.SemanticKernel.SkillDefinition;
using Microsoft.SemanticKernel.Skills.Grpc.Model;
using Microsoft.SemanticKernel.Skills.Grpc.Protobuf;

namespace Microsoft.SemanticKernel.Skills.Grpc.Extensions;

/// <summary>
/// <see cref="IKernel"/> extensions methods for gRPC functionality.
/// </summary>
public static class KernelGrpcExtensions
{
/// <summary>
/// Imports gRPC document from a directory.
/// </summary>
/// <param name="kernel">Semantic Kernel instance.</param>
/// <param name="parentDirectory">Directory containing the skill directory.</param>
/// <param name="skillDirectoryName">Name of the directory containing the selected skill.</param>
/// <returns>A list of all the semantic functions representing the skill.</returns>
public static IDictionary<string, ISKFunction> ImportGrpcSkillFromDirectory(this IKernel kernel, string parentDirectory, string skillDirectoryName)
{
const string PROTO_FILE = "grpc.proto";

Verify.ValidSkillName(skillDirectoryName);

var skillDir = Path.Combine(parentDirectory, skillDirectoryName);
Verify.DirectoryExists(skillDir);

var filePath = Path.Combine(skillDir, PROTO_FILE);
if (!File.Exists(filePath))
{
throw new FileNotFoundException($"No .proto document for the specified path - {filePath} is found.");
}

kernel.Log.LogTrace("Registering gRPC functions from {0} .proto document.", filePath);

using var stream = File.OpenRead(filePath);

return kernel.RegisterGrpcSkill(stream, skillDirectoryName);
}

/// <summary>
/// Imports gRPC document from a file.
/// </summary>
/// <param name="kernel">Semantic Kernel instance.</param>
/// <param name="skillName">Name of the skill to register.</param>
/// <param name="filePath">File path to .proto document.</param>
/// <returns>A list of all the semantic functions representing the skill.</returns>
public static IDictionary<string, ISKFunction> ImportGrpcSkillFromFile(
this IKernel kernel,
string skillName,
string filePath)
{
if (!File.Exists(filePath))
{
throw new FileNotFoundException($"No .proto document for the specified path - {filePath} is found.");
}

kernel.Log.LogTrace("Registering gRPC functions from {0} .proto document.", filePath);

using var stream = File.OpenRead(filePath);

return kernel.RegisterGrpcSkill(stream, skillName);
}

/// <summary>
/// Registers an gRPC skill.
/// </summary>
/// <param name="kernel">Semantic Kernel instance.</param>
/// <param name="documentStream">.proto document stream.</param>
/// <param name="skillName">Skill name.</param>
/// <returns>A list of all the semantic functions representing the skill.</returns>
public static IDictionary<string, ISKFunction> RegisterGrpcSkill(
this IKernel kernel,
Stream documentStream,
string skillName)
{
Verify.NotNull(kernel, nameof(kernel));
Verify.ValidSkillName(skillName);

// Parse
var parser = new ProtoDocumentParser();

var operations = parser.Parse(documentStream, skillName);

var skill = new Dictionary<string, ISKFunction>();

var runner = new GrpcOperationRunner(new HttpClient());

foreach (var operation in operations)
{
try
{
kernel.Log.LogTrace("Registering gRPC function {0}.{1}", skillName, operation.Name);
var function = kernel.RegisterGrpcFunction(runner, skillName, operation);
skill[function.Name] = function;
}
catch (Exception ex) when (!ex.IsCriticalException())
{
//Logging the exception and keep registering other gRPC functions
kernel.Log.LogWarning(ex, "Something went wrong while rendering the gRPC function. Function: {0}.{1}. Error: {2}",
skillName, operation.Name, ex.Message);
}
}

return skill;
}

#region private

/// <summary>
/// Registers SKFunction for a gRPC operation.
/// </summary>
/// <param name="kernel">Semantic Kernel instance.</param>
/// <param name="runner">gRPC operation runner.</param>
/// <param name="skillName">Skill name.</param>
/// <param name="operation">The gRPC operation.</param>
/// <returns>An instance of <see cref="SKFunction"/> class.</returns>
private static ISKFunction RegisterGrpcFunction(
this IKernel kernel,
GrpcOperationRunner runner,
string skillName,
GrpcOperation operation)
{
var operationParameters = operation.GetParameters();

async Task<SKContext> ExecuteAsync(SKContext context)
{
try
{
var arguments = new Dictionary<string, string>();

//Extract function arguments from context
foreach (var parameter in operationParameters)
{
//A try to resolve argument parameter name.
if (context.Variables.Get(parameter.Name, out var value))
{
arguments.Add(parameter.Name, value);
continue;
}

throw new KeyNotFoundException($"No variable found in context to use as an argument for the '{parameter.Name}' parameter of the '{skillName}.{operation.Name}' gRPC function.");
}

//SKFunction should be extended to pass cancellation token for delegateFunction calls.
var result = await runner.RunAsync(operation, arguments, CancellationToken.None).ConfigureAwait(false);

if (result != null)
{
context.Variables.Update(result.ToString());
}
}
catch (Exception ex) when (!ex.IsCriticalException())
{
kernel.Log.LogWarning(ex, "Something went wrong while rendering the gRPC function. Function: {0}.{1}. Error: {2}", skillName, operation.Name,
ex.Message);
context.Fail(ex.Message, ex);
}

return context;
}

#pragma warning disable CA2000 // Dispose objects before losing scope.
var function = new SKFunction(
delegateType: SKFunction.DelegateTypes.ContextSwitchInSKContextOutTaskSKContext,
delegateFunction: ExecuteAsync,
parameters: operationParameters.ToList(),
description: operation.Name,
skillName: skillName,
functionName: operation.Name,
isSemantic: false,
log: kernel.Log);
#pragma warning restore CA2000 // Dispose objects before losing scope

return kernel.RegisterCustomFunction(skillName, function);
}

#endregion
}