A programming framework for agentic AI
now it builds
Ryan Sweeta888337724b0
diff --git a/Elsa.SemanticKernel/Activities/SemanticKernelSkillRequest.cs b/Elsa.SemanticKernel/Activities/SemanticKernelSkillRequest.csnew file mode 100644index 000000000..bb5a11fff--- /dev/null+++ b/Elsa.SemanticKernel/Activities/SemanticKernelSkillRequest.cs@@ -0,0 +1,119 @@+using Elsa.Extensions;+using Elsa.Workflows.Core;+using Elsa.Workflows.Core.Attributes;+using Elsa.Workflows.Core.Models;+using JetBrains.Annotations;+using Microsoft.Extensions.Logging;+using Microsoft.SemanticKernel;+using Microsoft.SemanticKernel.Connectors.Memory.Qdrant;+using Microsoft.SemanticKernel.Connectors.AI.OpenAI.TextEmbedding;+using Microsoft.SemanticKernel.Memory;+using Microsoft.SemanticKernel.Orchestration;+using Microsoft.SemanticKernel.Reliability;+namespace Elsa.SemanticKernel;+using System;+using System.Text.Json;+using System.Threading.Tasks;+using skills;++/// <summary>+/// Invoke a Semantic Kernel skill.+/// </summary>+[Activity("Elsa", "SemanticKernelSkill", "Invoke a Semantic Kernel skill. ", DisplayName = "Semantic Kernel Skill", Kind = ActivityKind.Task)]+[PublicAPI]+public class SemanticKernelSkill : CodeActivity<string>+{+ [Input(+ Description = "System Prompt.",+ UIHint = InputUIHints.MultiText,+ DefaultValue = new string[0])]+ public Input<string> SystemPrompt { get; set; } = default!;++ [Input(+ Description = "User Input Prompt.",+ UIHint = InputUIHints.MultiText,+ DefaultValue = new string[0])]+ public Input<string> Prompt { get; set; }++ [Input(+ Description = "Max retries",+ UIHint = InputUIHints.SingleLine,+ DefaultValue = 9)]+ public Input<int> MaxRetries { get; set; }++ [Input(+ Description = "The skill to invoke from the semantic kernel",+ UIHint = InputUIHints.SingleLine,+ DefaultValue = "PM")]+ public Input<string> SkillName { get; set; }++ [Input(+ Description = "The function to invoke from the skill",+ UIHint = InputUIHints.SingleLine,+ DefaultValue = "README")]+ public Input<string> FunctionName { get; set; }++ /// <inheritdoc />+ protected override async ValueTask ExecuteAsync(ActivityExecutionContext context)+ {+ var skillName = SkillName.Get(context);+ var functionName = FunctionName.Get(context);+ var systemPrompt = SystemPrompt.Get(context);+ var prompt = Prompt.Get(context);+ var maxRetries = MaxRetries.Get(context);+ var result = await ChatCompletion<string>(skillName, functionName, prompt, maxRetries);+ context.SetResult(result);+ }++ private async Task<T> ChatCompletion<T>(string skillName, string functionName, string prompt, int maxRetries)+ {+ var kernelSettings = KernelSettings.LoadSettings();+ var kernelConfig = new KernelConfig();++ using ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>+ {+ builder+ .SetMinimumLevel(kernelSettings.LogLevel ?? LogLevel.Warning);+ });+ /* var memoryStore = new QdrantMemoryStore(new QdrantVectorDbClient("http://qdrant", 1536, port: 6333));+ var embedingGeneration = new AzureTextEmbeddingGeneration(kernelSettings.EmbeddingDeploymentOrModelId, kernelSettings.Endpoint, kernelSettings.ApiKey);+ var semanticTextMemory = new SemanticTextMemory(memoryStore, embedingGeneration);+ */+ var kernel = new KernelBuilder()+ .WithLogger(loggerFactory.CreateLogger<IKernel>())+ .WithAzureChatCompletionService(kernelSettings.DeploymentOrModelId, kernelSettings.Endpoint, kernelSettings.ApiKey, true, kernelSettings.ServiceId, true)+ //.WithMemory(semanticTextMemory)+ .WithConfiguration(kernelConfig)+ .Configure(c => c.SetDefaultHttpRetryConfig(new HttpRetryConfig+ {+ MaxRetryCount = maxRetries,+ UseExponentialBackoff = true,+ // MinRetryDelay = TimeSpan.FromSeconds(2),+ // MaxRetryDelay = TimeSpan.FromSeconds(8),+ MaxTotalRetryTime = TimeSpan.FromSeconds(300),+ // RetryableStatusCodes = new[] { HttpStatusCode.TooManyRequests, HttpStatusCode.RequestTimeout },+ // RetryableExceptions = new[] { typeof(HttpRequestException) }+ }))+ .Build();++/* var interestingMemories = kernel.Memory.SearchAsync("ImportedMemories", prompt, 2);+ var wafContext = "Consider the following contextual snippets:";+ await foreach (var memory in interestingMemories)+ {+ wafContext += $"\n {memory.Metadata.Text}";+ } */++ var skillConfig = SemanticFunctionConfig.ForSkillAndFunction(skillName, functionName);+ var function = kernel.CreateSemanticFunction(skillConfig.PromptTemplate, skillConfig.Name, skillConfig.SkillName,+ skillConfig.Description, skillConfig.MaxTokens, skillConfig.Temperature,+ skillConfig.TopP, skillConfig.PPenalty, skillConfig.FPenalty);++ var context = new ContextVariables();+ context.Set("input", prompt);+ context.Set("wafContext", wafContext);++ var answer = await kernel.RunAsync(context, function).ConfigureAwait(false);+ var result = typeof(T) != typeof(string) ? JsonSerializer.Deserialize<T>(answer.ToString()) : (T)(object)answer.ToString();+ return result;+ }+}\ No newline at end of filediff --git a/Elsa.SemanticKernel/Config/KernelConfigExtensions.cs b/Elsa.SemanticKernel/Config/KernelConfigExtensions.csnew file mode 100644index 000000000..92b8392ef--- /dev/null+++ b/Elsa.SemanticKernel/Config/KernelConfigExtensions.cs@@ -0,0 +1,27 @@+using Microsoft.SemanticKernel;++internal static class KernelConfigExtensions+{+ /// <summary>+ /// Adds a text completion service to the list. It can be either an OpenAI or Azure OpenAI backend service.+ /// </summary>+ /// <param name="kernelConfig"></param>+ /// <param name="kernelSettings"></param>+ /// <exception cref="Exception"></exception>+ internal static void AddCompletionBackend(this KernelConfig kernelConfig, KernelSettings kernelSettings)+ {+ switch (kernelSettings.ServiceType.ToUpperInvariant())+ {+ case KernelSettings.AzureOpenAI:+ kernelConfig.AddAzureChatCompletionService(kernelSettings.DeploymentOrModelId, kernelSettings.Endpoint, kernelSettings.ApiKey);+ break;++ case KernelSettings.OpenAI:+ kernelConfig.AddOpenAITextCompletionService(modelId: kernelSettings.DeploymentOrModelId, apiKey: kernelSettings.ApiKey, orgId: kernelSettings.OrgId, serviceId: kernelSettings.ServiceId);+ break;++ default:+ throw new System.Exception($"Invalid service type value: {kernelSettings.ServiceType}");+ }+ }+}diff --git a/Elsa.SemanticKernel/Config/KernelSettings.cs b/Elsa.SemanticKernel/Config/KernelSettings.csnew file mode 100644index 000000000..613c2c92e--- /dev/null+++ b/Elsa.SemanticKernel/Config/KernelSettings.cs@@ -0,0 +1,95 @@+using System.Text.Json.Serialization;+using Microsoft.Extensions.Configuration;+using Microsoft.Extensions.Logging;+using System.IO;+using System;+++internal class KernelSettings+{+ public const string DefaultConfigFile = "config/appsettings.json";+ public const string OpenAI = "OPENAI";+ public const string AzureOpenAI = "AZUREOPENAI";++ [JsonPropertyName("serviceType")]+ public string ServiceType { get; set; } = string.Empty;++ [JsonPropertyName("serviceId")]+ public string ServiceId { get; set; } = string.Empty;++ [JsonPropertyName("deploymentOrModelId")]+ public string DeploymentOrModelId { get; set; } = string.Empty;+ [JsonPropertyName("embeddingDeploymentOrModelId")]+ public string EmbeddingDeploymentOrModelId { get; set; } = string.Empty;++ [JsonPropertyName("endpoint")]+ public string Endpoint { get; set; } = string.Empty;++ [JsonPropertyName("apiKey")]+ public string ApiKey { get; set; } = string.Empty;++ [JsonPropertyName("orgId")]+ public string OrgId { get; set; } = string.Empty;++ [JsonPropertyName("logLevel")]+ public LogLevel? LogLevel { get; set; }++ /// <summary>+ /// Load the kernel settings from settings.json if the file exists and if not attempt to use user secrets.+ /// </summary>+ internal static KernelSettings LoadSettings()+ {+ try+ {+ if (File.Exists(DefaultConfigFile))+ {+ return FromFile(DefaultConfigFile);+ }++ Console.WriteLine($"Semantic kernel settings '{DefaultConfigFile}' not found, attempting to load configuration from user secrets.");++ return FromUserSecrets();+ }+ catch (InvalidDataException ide)+ {+ Console.Error.WriteLine(+ "Unable to load semantic kernel settings, please provide configuration settings using instructions in the README.\n" ++ "Please refer to: https://github.com/microsoft/semantic-kernel-starters/blob/main/sk-csharp-hello-world/README.md#configuring-the-starter"+ );+ throw new InvalidOperationException(ide.Message);+ }+ }++ /// <summary>+ /// Load the kernel settings from the specified configuration file if it exists.+ /// </summary>+ internal static KernelSettings FromFile(string configFile = DefaultConfigFile)+ {+ if (!File.Exists(configFile))+ {+ throw new FileNotFoundException($"Configuration not found: {configFile}");+ }++ var configuration = new ConfigurationBuilder()+ .SetBasePath(System.IO.Directory.GetCurrentDirectory())+ .AddJsonFile(configFile, optional: true, reloadOnChange: true)+ .Build();++ return configuration.Get<KernelSettings>()+ ?? throw new InvalidDataException($"Invalid semantic kernel settings in '{configFile}', please provide configuration settings using instructions in the README.");+ }++ /// <summary>+ /// Load the kernel settings from user secrets.+ /// </summary>+ internal static KernelSettings FromUserSecrets()+ {+ var configuration = new ConfigurationBuilder()+ .AddUserSecrets<KernelSettings>()+ .AddEnvironmentVariables()+ .Build();++ return configuration.Get<KernelSettings>()+ ?? throw new InvalidDataException("Invalid semantic kernel settings in user secrets, please provide configuration settings using instructions in the README.");+ }+}diff --git a/Elsa.SemanticKernel/Elsa.SemanticKernel.csproj b/Elsa.SemanticKernel/Elsa.SemanticKernel.csprojnew file mode 100644index 000000000..8b4fb761f--- /dev/null+++ b/Elsa.SemanticKernel/Elsa.SemanticKernel.csproj@@ -0,0 +1,26 @@+<Project Sdk="Microsoft.NET.Sdk">++ <PropertyGroup>+ <TargetFrameworks>net7.0</TargetFrameworks>+ <Description>+ Activities for calling Semantic Kernel SDK+ </Description>+ <PackageTags>elsa module semantic kerne activities</PackageTags>+ </PropertyGroup>++ <ItemGroup>+ <PackageReference Include="Elsa" Version="3.0.0-rc1" />+ <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="7.0.0" />+ <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />+ <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" />+ <PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />+ <PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />+ <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="7.0.0" />+ <PackageReference Include="AspNetCore.Authentication.ApiKey" Version="7.0.0" />+ <PackageReference Include="Microsoft.SemanticKernel" Version="0.17.230704.3-preview" />+ <PackageReference Include="Microsoft.SemanticKernel.Connectors.Memory.Qdrant" Version="0.17.230704.3-preview" />+ <ProjectReference Include="..\skills\skills.csproj" />++ </ItemGroup>++</Project>diff --git a/Elsa.SemanticKernel/Elsa.SemanticKernel.csproj.DotSettings b/Elsa.SemanticKernel/Elsa.SemanticKernel.csproj.DotSettingsnew file mode 100644index 000000000..875c6b6a6--- /dev/null+++ b/Elsa.SemanticKernel/Elsa.SemanticKernel.csproj.DotSettings@@ -0,0 +1,4 @@+<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">+ <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=activities/@EntryIndexedValue">True</s:Boolean>+ <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=activities_005Chttpendpoint/@EntryIndexedValue">True</s:Boolean>+ <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=activities_005Chttptrigger/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>\ No newline at end of filediff --git a/Elsa.SemanticKernel/Elsa.SemanticKernel.sln b/Elsa.SemanticKernel/Elsa.SemanticKernel.slnnew file mode 100644index 000000000..1873647b9--- /dev/null+++ b/Elsa.SemanticKernel/Elsa.SemanticKernel.sln@@ -0,0 +1,25 @@++Microsoft Visual Studio Solution File, Format Version 12.00+# Visual Studio Version 16+VisualStudioVersion = 25.0.1705.3+MinimumVisualStudioVersion = 10.0.40219.1+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Elsa.SemanticKernel", "Elsa.SemanticKernel.csproj", "{9B5A7ECD-F83F-4AF2-8FD7-413FBFEE9509}"+EndProject+Global+ GlobalSection(SolutionConfigurationPlatforms) = preSolution+ Debug|Any CPU = Debug|Any CPU+ Release|Any CPU = Release|Any CPU+ EndGlobalSection+ GlobalSection(ProjectConfigurationPlatforms) = postSolution+ {9B5A7ECD-F83F-4AF2-8FD7-413FBFEE9509}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {9B5A7ECD-F83F-4AF2-8FD7-413FBFEE9509}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {9B5A7ECD-F83F-4AF2-8FD7-413FBFEE9509}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {9B5A7ECD-F83F-4AF2-8FD7-413FBFEE9509}.Release|Any CPU.Build.0 = Release|Any CPU+ EndGlobalSection+ GlobalSection(SolutionProperties) = preSolution+ HideSolutionNode = FALSE+ EndGlobalSection+ GlobalSection(ExtensibilityGlobals) = postSolution+ SolutionGuid = {EDCC8E64-CF64-4C18-A00D-43F896A0C8FD}+ EndGlobalSection+EndGlobaldiff --git a/Elsa.SemanticKernel/NuGet.Config b/Elsa.SemanticKernel/NuGet.Confignew file mode 100644index 000000000..a89a1e8b5--- /dev/null+++ b/Elsa.SemanticKernel/NuGet.Config@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="utf-8"?>+<configuration>+ <packageSources>+ <clear/>++ <add key="NuGet official package source" value="https://api.nuget.org/v3/index.json" />+ <add key="Jint prereleases" value="https://www.myget.org/F/jint/api/v3/index.json" />+ <add key="Elsa prereleases" value="https://f.feedz.io/elsa-workflows/elsa-3/nuget/index.json" />+ </packageSources>+</configuration>\ No newline at end of file