Skip to content

A programming framework for agentic AI

Understanding experiments (#9)

Kosta Petan6fd192949847
diff --git a/src/apps/cli/Program.cs b/src/apps/cli/Program.cs
index 5d18ee5b1..e43c6609c 100644
--- a/src/apps/cli/Program.cs
+++ b/src/apps/cli/Program.cs
@@ -3,10 +3,12 @@ using System.Text.Json;
using Microsoft.AI.DevTeam.Skills;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
+using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
using Microsoft.SemanticKernel.Connectors.AI.OpenAI.TextEmbedding;
using Microsoft.SemanticKernel.Connectors.Memory.Qdrant;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Orchestration;
+using Microsoft.SemanticKernel.Plugins.Memory;
class Program
@@ -139,25 +141,30 @@ class Program
var embedingGeneration = new AzureTextEmbeddingGeneration(kernelSettings.EmbeddingDeploymentOrModelId, kernelSettings.Endpoint, kernelSettings.ApiKey);
var semanticTextMemory = new SemanticTextMemory(memoryStore, embedingGeneration);
+
+
+ var memoryBuilder = new MemoryBuilder();
+ var memory = memoryBuilder.WithLoggerFactory(loggerFactory)
+ .WithQdrantMemoryStore("http://qdrant:6333", 1536)
+ .WithAzureTextEmbeddingGenerationService(kernelSettings.EmbeddingDeploymentOrModelId, kernelSettings.Endpoint, kernelSettings.ApiKey)
+ .Build();
+
var kernel = new KernelBuilder()
.WithLoggerFactory(loggerFactory)
.WithAzureChatCompletionService(kernelSettings.DeploymentOrModelId, kernelSettings.Endpoint, kernelSettings.ApiKey, true, kernelSettings.ServiceId, true)
- .WithMemory(semanticTextMemory)
.Build();
//Console.WriteLine($"Calling skill '{skillName}' function '{functionName}' with input '{input}'");
- var interestingMemories = kernel.Memory.SearchAsync("waf-pages", input, 2);
+ var interestingMemories = memory.SearchAsync("waf-pages", input, 2);
var wafContext = "Consider the following architectural guidelines:";
- await foreach (var memory in interestingMemories)
+ await foreach (var m in interestingMemories)
{
- wafContext += $"\n {memory.Metadata.Text}";
+ wafContext += $"\n {m.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 promptTemplate = Skills.ForSkillAndFunction(skillName, functionName);
+ var function = kernel.CreateSemanticFunction(promptTemplate);
var context = new ContextVariables();
context.Set("input", input);
diff --git a/src/apps/cli/SandboxSkill.cs b/src/apps/cli/SandboxSkill.cs
index a44782a13..918a722e9 100644
--- a/src/apps/cli/SandboxSkill.cs
+++ b/src/apps/cli/SandboxSkill.cs
@@ -1,5 +1,4 @@
using DotNet.Testcontainers.Builders;
-using Microsoft.SemanticKernel.SkillDefinition;
public class SandboxSkill
{
diff --git a/src/apps/cli/cli.csproj b/src/apps/cli/cli.csproj
index d1bfcd0ad..b930ed06f 100644
--- a/src/apps/cli/cli.csproj
+++ b/src/apps/cli/cli.csproj
@@ -13,8 +13,8 @@
<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.SemanticKernel" Version="0.24.230918.1-preview" />
- <PackageReference Include="Microsoft.SemanticKernel.Connectors.Memory.Qdrant" Version="0.24.230918.1-preview" />
+ <PackageReference Include="Microsoft.SemanticKernel" Version="1.0.0-beta5" />
+ <PackageReference Include="Microsoft.SemanticKernel.Connectors.Memory.Qdrant" Version="1.0.0-beta5" />
<PackageReference Include="Testcontainers" Version="3.2.0" />
<ProjectReference Include="..\..\libs\Microsoft.AI.DevTeam.Skills\Microsoft.AI.DevTeam.Skills.csproj" />
</ItemGroup>
diff --git a/src/apps/gh-flow-df/Services/WebHookEventProcessor.cs b/src/apps/gh-flow-df/Services/WebHookEventProcessor.cs
index 70168f5dd..f2d25a05b 100644
--- a/src/apps/gh-flow-df/Services/WebHookEventProcessor.cs
+++ b/src/apps/gh-flow-df/Services/WebHookEventProcessor.cs
@@ -3,6 +3,7 @@ using System.Text;
using Microsoft.AI.DevTeam.Skills;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
+using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
using Microsoft.SemanticKernel.Orchestration;
using Newtonsoft.Json;
using Octokit.Webhooks;
@@ -96,10 +97,8 @@ public class SKWebHookEventProcessor : WebhookEventProcessor
private async Task<string> RunSkill(string skillName, string functionName, string input)
{
- 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 prompt = Skills.ForSkillAndFunction(skillName, functionName);
+ var function = _kernel.CreateSemanticFunction(prompt, new OpenAIRequestSettings { MaxTokens = 8000, Temperature = 0.4, TopP = 1 });
var interestingMemories = _kernel.Memory.SearchAsync("waf-pages", input, 2);
var wafContext = "Consider the following architectural guidelines:";
diff --git a/src/apps/gh-flow-df/gh-flow-df.csproj b/src/apps/gh-flow-df/gh-flow-df.csproj
index aba8a20b4..07d73342f 100644
--- a/src/apps/gh-flow-df/gh-flow-df.csproj
+++ b/src/apps/gh-flow-df/gh-flow-df.csproj
@@ -27,8 +27,8 @@
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.19.0" />
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.21.0" />
<PackageReference Include="Octokit.Webhooks.AzureFunctions" Version="2.0.3" />
- <PackageReference Include="Microsoft.SemanticKernel" Version="0.24.230918.1-preview" />
- <PackageReference Include="Microsoft.SemanticKernel.Connectors.Memory.Qdrant" Version="0.24.230918.1-preview" />
+ <PackageReference Include="Microsoft.SemanticKernel" Version="1.0.0-beta5" />
+ <PackageReference Include="Microsoft.SemanticKernel.Connectors.Memory.Qdrant" Version="1.0.0-beta5" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Storage" Version="5.0.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Tables" Version="1.2.0" />
<PackageReference Include="Octokit" Version="7.1.0" />
diff --git a/src/apps/gh-flow/Program.cs b/src/apps/gh-flow/Program.cs
index 1a7418828..5118598e7 100644
--- a/src/apps/gh-flow/Program.cs
+++ b/src/apps/gh-flow/Program.cs
@@ -1,10 +1,14 @@
using System.Text.Json;
+using Azure;
+using Azure.AI.OpenAI;
using Microsoft.AI.DevTeam;
using Microsoft.Extensions.Options;
using Microsoft.SemanticKernel;
-using Microsoft.SemanticKernel.Connectors.AI.OpenAI.TextEmbedding;
+using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
using Microsoft.SemanticKernel.Connectors.Memory.Qdrant;
using Microsoft.SemanticKernel.Memory;
+using Microsoft.SemanticKernel.Plugins.Memory;
+using Microsoft.SemanticKernel.Reliability.Basic;
using Octokit.Webhooks;
using Octokit.Webhooks.AspNetCore;
using Orleans.Configuration;
@@ -12,12 +16,14 @@ using Orleans.Configuration;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<WebhookEventProcessor, GithubWebHookProcessor>();
builder.Services.AddTransient(CreateKernel);
+builder.Services.AddTransient(CreateMemory);
builder.Services.AddHttpClient();
builder.Services.AddSingleton(s =>
{
var ghOptions = s.GetService<IOptions<GithubOptions>>();
- var ghService = new GithubAuthService(ghOptions);
+ var logger = s.GetService<ILogger<GithubAuthService>>();
+ var ghService = new GithubAuthService(ghOptions, logger);
var client = ghService.GetGitHubClient().Result;
return client;
});
@@ -140,7 +146,7 @@ app.UseEndpoints(endpoints =>
app.Run();
-static IKernel CreateKernel(IServiceProvider provider)
+static ISemanticTextMemory CreateMemory(IServiceProvider provider)
{
var openAiConfig = provider.GetService<IOptions<OpenAIOptions>>().Value;
var qdrantConfig = provider.GetService<IOptions<QdrantOptions>>().Value;
@@ -153,12 +159,34 @@ static IKernel CreateKernel(IServiceProvider provider)
.AddDebug();
});
- var memoryStore = new QdrantMemoryStore(new QdrantVectorDbClient(qdrantConfig.Endpoint, qdrantConfig.VectorSize));
- var embedingGeneration = new AzureTextEmbeddingGeneration(openAiConfig.EmbeddingDeploymentOrModelId, openAiConfig.Endpoint, openAiConfig.ApiKey);
- var semanticTextMemory = new SemanticTextMemory(memoryStore, embedingGeneration);
+ var memoryBuilder = new MemoryBuilder();
+ return memoryBuilder.WithLoggerFactory(loggerFactory)
+ .WithQdrantMemoryStore(qdrantConfig.Endpoint, qdrantConfig.VectorSize)
+ .WithAzureTextEmbeddingGenerationService(openAiConfig.EmbeddingDeploymentOrModelId, openAiConfig.Endpoint, openAiConfig.ApiKey)
+ .Build();
+}
+
+static IKernel CreateKernel(IServiceProvider provider)
+{
+ var openAiConfig = provider.GetService<IOptions<OpenAIOptions>>().Value;
+
+ var loggerFactory = LoggerFactory.Create(builder =>
+ {
+ builder
+ .SetMinimumLevel(LogLevel.Debug)
+ .AddConsole()
+ .AddDebug();
+ });
+
+ var clientOptions = new OpenAIClientOptions();
+ clientOptions.Retry.NetworkTimeout = TimeSpan.FromMinutes(5);
+ var openAIClient = new OpenAIClient(new Uri(openAiConfig.Endpoint), new AzureKeyCredential(openAiConfig.ApiKey), clientOptions);
return new KernelBuilder()
.WithLoggerFactory(loggerFactory)
- .WithAzureChatCompletionService(openAiConfig.DeploymentOrModelId, openAiConfig.Endpoint, openAiConfig.ApiKey, true, openAiConfig.ServiceId, true)
- .WithMemory(semanticTextMemory).Build();
+ .WithAzureChatCompletionService(openAiConfig.DeploymentOrModelId, openAIClient)
+ .WithRetryBasic(new BasicRetryConfig {
+ MaxRetryCount = 5,
+ UseExponentialBackoff = true
+ }).Build();
}
\ No newline at end of file
diff --git a/src/apps/gh-flow/Services/GithubWebHookProcessor.cs b/src/apps/gh-flow/Services/GithubWebHookProcessor.cs
index 708e7bff1..d223dc380 100644
--- a/src/apps/gh-flow/Services/GithubWebHookProcessor.cs
+++ b/src/apps/gh-flow/Services/GithubWebHookProcessor.cs
@@ -211,7 +211,7 @@ public sealed class GithubWebHookProcessor : WebhookEventProcessor
Org = org,
Repo = repo,
Number = (int)issueNumber,
- Content = readme
+ Content = string.IsNullOrEmpty(readme)? "Sorry, something went wrong": readme
});
}
else if (skillName == nameof(DevLead) && functionName == nameof(DevLead.Plan))
@@ -223,19 +223,20 @@ public sealed class GithubWebHookProcessor : WebhookEventProcessor
Org = org,
Repo = repo,
Number = (int)issueNumber,
- Content = plan
+ Content = string.IsNullOrEmpty(plan)? "Sorry, something went wrong":plan
});
}
else if (skillName == nameof(Developer) && functionName == nameof(Developer.Implement))
{
var dev = _grains.GetGrain<IDevelopCode>(issueNumber, suffix);
var code = await dev.GenerateCode(input);
+
await _ghService.PostComment(new PostCommentRequest
{
Org = org,
Repo = repo,
Number = (int)issueNumber,
- Content = code
+ Content = string.IsNullOrEmpty(code)? "Sorry, something went wrong":code
});
}
else { }// something went wrong
diff --git a/src/apps/gh-flow/appsettings.template.json b/src/apps/gh-flow/appsettings.template.json
index 78d23c1f2..8877352b6 100644
--- a/src/apps/gh-flow/appsettings.template.json
+++ b/src/apps/gh-flow/appsettings.template.json
@@ -37,5 +37,8 @@
"QdrantOptions" : {
"Endpoint" : "http://qdrant:6333",
"VectorSize" : "1536"
+ },
+ "ServiceOptions" : {
+ "IngesterUrl" : "http://localhost:7071"
}
}
diff --git a/src/apps/gh-flow/gh-flow.csproj b/src/apps/gh-flow/gh-flow.csproj
index 3596510a5..cc7e902d1 100644
--- a/src/apps/gh-flow/gh-flow.csproj
+++ b/src/apps/gh-flow/gh-flow.csproj
@@ -15,7 +15,7 @@
<ItemGroup>
<PackageReference Include="Octokit.Webhooks.AspNetCore" Version="2.0.3" />
- <PackageReference Include="Microsoft.SemanticKernel.Connectors.Memory.Qdrant" Version="0.24.230918.1-preview" />
+ <PackageReference Include="Microsoft.SemanticKernel.Connectors.Memory.Qdrant" Version="1.0.0-beta5" />
<PackageReference Include="Microsoft.Orleans.Server" Version="7.2.1" />
<PackageReference Include="Microsoft.Orleans.Persistence.Cosmos" Version="7.2.1" />
<PackageReference Include="Microsoft.Orleans.Clustering.Cosmos" Version="7.2.1" />
diff --git a/src/apps/seed-memory/Program.cs b/src/apps/seed-memory/Program.cs
index 94342ef18..79e11cb59 100644
--- a/src/apps/seed-memory/Program.cs
+++ b/src/apps/seed-memory/Program.cs
@@ -1,13 +1,12 @@
using UglyToad.PdfPig;
using UglyToad.PdfPig.DocumentLayoutAnalysis.TextExtractor;
using Microsoft.SemanticKernel;
-using Microsoft.SemanticKernel.Text;
using Microsoft.Extensions.Logging;
-using System.Text;
using Microsoft.SemanticKernel.Connectors.Memory.Qdrant;
-using Microsoft.SemanticKernel.Connectors.AI.OpenAI.TextEmbedding;
using Microsoft.SemanticKernel.Memory;
using System.Reflection;
+using Microsoft.SemanticKernel.Plugins.Memory;
+using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
class Program
{
@@ -24,19 +23,15 @@ class Program
.AddDebug();
});
- var memoryStore = new QdrantMemoryStore(new QdrantVectorDbClient(kernelSettings.QdrantEndpoint, 1536));
- var embedingGeneration = new AzureTextEmbeddingGeneration(kernelSettings.EmbeddingDeploymentOrModelId, kernelSettings.Endpoint, kernelSettings.ApiKey);
- var semanticTextMemory = new SemanticTextMemory(memoryStore, embedingGeneration);
-
- var kernel = new KernelBuilder()
- .WithLoggerFactory(loggerFactory)
- .WithAzureChatCompletionService(kernelSettings.DeploymentOrModelId, kernelSettings.Endpoint, kernelSettings.ApiKey, true, kernelSettings.ServiceId, true)
- .WithMemory(semanticTextMemory)
- .Build();
- await ImportDocumentAsync(kernel, WafFileName);
+ var memoryBuilder = new MemoryBuilder();
+ var memory = memoryBuilder.WithLoggerFactory(loggerFactory)
+ .WithQdrantMemoryStore(kernelSettings.QdrantEndpoint, 1536)
+ .WithAzureTextEmbeddingGenerationService(kernelSettings.EmbeddingDeploymentOrModelId, kernelSettings.Endpoint, kernelSettings.ApiKey)
+ .Build();
+ await ImportDocumentAsync(memory, WafFileName);
}
- public static async Task ImportDocumentAsync(IKernel kernel, string filename)
+ public static async Task ImportDocumentAsync(ISemanticTextMemory memory, string filename)
{
var currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var filePath = Path.Combine(currentDirectory, filename);
@@ -48,7 +43,7 @@ class Program
{
var text = ContentOrderTextExtractor.GetText(page);
var descr = text.Take(100);
- await kernel.Memory.SaveInformationAsync(
+ await memory.SaveInformationAsync(
collection: "waf-pages",
text: text,
id: $"{Guid.NewGuid()}",
diff --git a/src/apps/seed-memory/seed-memory.csproj b/src/apps/seed-memory/seed-memory.csproj
index 5bb4ec8ec..e73fad29e 100644
--- a/src/apps/seed-memory/seed-memory.csproj
+++ b/src/apps/seed-memory/seed-memory.csproj
@@ -12,8 +12,8 @@
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
- <PackageReference Include="Microsoft.SemanticKernel" Version="0.24.230918.1-preview" />
- <PackageReference Include="Microsoft.SemanticKernel.Connectors.Memory.Qdrant" Version="0.24.230918.1-preview" />
+ <PackageReference Include="Microsoft.SemanticKernel" Version="1.0.0-beta5" />
+ <PackageReference Include="Microsoft.SemanticKernel.Connectors.Memory.Qdrant" Version="1.0.0-beta5" />
<PackageReference Include="PdfPig" Version="0.1.8-alpha-20230529-6daa2" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
</ItemGroup>
diff --git a/src/libs/Elsa.SemanticKernel/Activities/ActivityProviders/SemanticKernelSkillActivityProvider.cs b/src/libs/Elsa.SemanticKernel/Activities/ActivityProviders/SemanticKernelSkillActivityProvider.cs
index a6d1ced74..df2e56235 100644
--- a/src/libs/Elsa.SemanticKernel/Activities/ActivityProviders/SemanticKernelSkillActivityProvider.cs
+++ b/src/libs/Elsa.SemanticKernel/Activities/ActivityProviders/SemanticKernelSkillActivityProvider.cs
@@ -11,8 +11,8 @@ using Elsa.Workflows.Core.Models;
using Microsoft.AI.DevTeam.Skills;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
+using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
using Microsoft.SemanticKernel.Orchestration;
-using Microsoft.SemanticKernel.SkillDefinition;
namespace Elsa.SemanticKernel;
@@ -37,17 +37,14 @@ public class SemanticKernelActivityProvider : IActivityProvider
// get a list of skills in the assembly
var skills = LoadSkillsFromAssemblyAsync("skills", kernel);
SKContext context = kernel.CreateNewContext();
- var functionsAvailable = context.Skills.GetFunctionsView();
+ var functionsAvailable = context.Functions.GetFunctionViews();
// create activity descriptors for each skilland function
var activities = new List<ActivityDescriptor>();
- foreach (KeyValuePair<string, List<FunctionView>> skill in functionsAvailable.SemanticFunctions)
+ foreach (var function in functionsAvailable)
{
- Console.WriteLine($"Creating Activities for Skill: {skill.Key}");
- foreach (FunctionView func in skill.Value)
- {
- activities.Add(CreateActivityDescriptorFromSkillAndFunction(func, cancellationToken));
- }
+ Console.WriteLine($"Creating Activities for Plugin: {function.PluginName}");
+ activities.Add(CreateActivityDescriptorFromSkillAndFunction(function, cancellationToken));
}
return activities;
@@ -63,13 +60,13 @@ public class SemanticKernelActivityProvider : IActivityProvider
{
// Create a fully qualified type name for the activity
var thisNamespace = GetType().Namespace;
- var fullTypeName = $"{thisNamespace}.{function.SkillName}.{function.Name}";
+ var fullTypeName = $"{thisNamespace}.{function.PluginName}.{function.Name}";
Console.WriteLine($"Creating Activity: {fullTypeName}");
// create inputs from the function parameters - the SemanticKernelSkill activity will be the base for each activity
var inputs = new List<InputDescriptor>();
foreach (var p in function.Parameters) { inputs.Add(CreateInputDescriptorFromSKParameter(p)); }
- inputs.Add(CreateInputDescriptor(typeof(string), "SkillName", function.SkillName, "The name of the skill to use (generated, do not change)"));
+ inputs.Add(CreateInputDescriptor(typeof(string), "SkillName", function.PluginName, "The name of the skill to use (generated, do not change)"));
inputs.Add(CreateInputDescriptor(typeof(string), "FunctionName", function.Name, "The name of the function to use (generated, do not change)"));
inputs.Add(CreateInputDescriptor(typeof(int), "MaxRetries", KernelSettings.DefaultMaxRetries, "Max Retries to contact AI Service"));
@@ -80,8 +77,8 @@ public class SemanticKernelActivityProvider : IActivityProvider
Description = function.Description,
Name = function.Name,
TypeName = fullTypeName,
- Namespace = $"{thisNamespace}.{function.SkillName}",
- DisplayName = $"{function.SkillName}.{function.Name}",
+ Namespace = $"{thisNamespace}.{function.PluginName}",
+ DisplayName = $"{function.PluginName}.{function.Name}",
Inputs = inputs,
Outputs = new[] {new OutputDescriptor()},
Constructor = context =>
@@ -95,7 +92,7 @@ public class SemanticKernelActivityProvider : IActivityProvider
activityInstance.Type = fullTypeName;
// Configure the activity's URL and method properties.
- activityInstance.SkillName = new Input<string?>(function.SkillName);
+ activityInstance.SkillName = new Input<string?>(function.PluginName);
activityInstance.FunctionName = new Input<string?>(function.Name);
return activityInstance;
@@ -169,19 +166,11 @@ public class SemanticKernelActivityProvider : IActivityProvider
string field = function.FieldType.ToString();
if (field.Equals("Microsoft.SKDevTeam.SemanticFunctionConfig"))
{
- var skillConfig = SemanticFunctionConfig.ForSkillAndFunction(skillType.Name, function.Name);
+ var promptTemplate = Skills.ForSkillAndFunction(skillType.Name, function.Name);
var skfunc = kernel.CreateSemanticFunction(
- skillConfig.PromptTemplate,
- skillConfig.Name,
- skillConfig.SkillName,
- skillConfig.Description,
- skillConfig.MaxTokens,
- skillConfig.Temperature,
- skillConfig.TopP,
- skillConfig.PPenalty,
- skillConfig.FPenalty);
-
- Console.WriteLine($"SKActivityProvider Added SK function: {skfunc.SkillName}.{skfunc.Name}");
+ promptTemplate, new OpenAIRequestSettings { MaxTokens = 8000, Temperature = 0.4, TopP = 1 });
+
+ Console.WriteLine($"SKActivityProvider Added SK function: {skfunc.PluginName}.{skfunc.Name}");
}
}
}
diff --git a/src/libs/Elsa.SemanticKernel/Activities/SemanticKernel.cs b/src/libs/Elsa.SemanticKernel/Activities/SemanticKernel.cs
index 4ba5f8cbc..e81da076b 100644
--- a/src/libs/Elsa.SemanticKernel/Activities/SemanticKernel.cs
+++ b/src/libs/Elsa.SemanticKernel/Activities/SemanticKernel.cs
@@ -6,7 +6,6 @@ using JetBrains.Annotations;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Orchestration;
-using Microsoft.SemanticKernel.SkillDefinition;
using System;
using System.Text;
@@ -15,6 +14,7 @@ using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AI.DevTeam.Skills;
+using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
namespace Elsa.SemanticKernel;
@@ -86,11 +86,9 @@ public class SemanticKernelSkill : CodeActivity<string>
var kernel = KernelBuilder();
// load the skill
- var skillConfig = SemanticFunctionConfig.ForSkillAndFunction(skillName, functionName);
+ var promptTemplate = Skills.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 function = kernel.CreateSemanticFunction(promptTemplate, new OpenAIRequestSettings { MaxTokens = 8000, Temperature = 0.4, TopP = 1 });
// set the context (our prompt)
var contextVars = new ContextVariables();
@@ -106,10 +104,8 @@ public class SemanticKernelSkill : CodeActivity<string>
//context.Set("wafContext", wafContext);
- SKContext answer = await kernel.RunAsync(contextVars, function).ConfigureAwait(false);
- string result = answer.Result;
-
- workflowContext.SetResult(result);
+ var answer = await kernel.RunAsync(contextVars, function);
+ workflowContext.SetResult(answer);
}
}
@@ -121,36 +117,34 @@ public class SemanticKernelSkill : CodeActivity<string>
var theSkills = LoadSkillsFromAssemblyAsync("skills", kernel);
SKContext context = kernel.CreateNewContext();
- var functionsAvailable = context.Skills.GetFunctionsView();
+ var functionsAvailable = context.Functions.GetFunctionViews();
var list = new StringBuilder();
- foreach (KeyValuePair<string, List<FunctionView>> skill in functionsAvailable.SemanticFunctions)
+ foreach (var function in functionsAvailable)
{
- Console.WriteLine($"Skill: {skill.Key}");
- foreach (FunctionView func in skill.Value)
- {
+ Console.WriteLine($"Skill: {function.PluginName}");
+
// Function description
- if (func.Description != null)
+ if (function.Description != null)
{
- list.AppendLine($"// {func.Description}");
+ list.AppendLine($"// {function.Description}");
}
else
{
- Console.WriteLine("{0}.{1} is missing a description", func.SkillName, func.Name);
- list.AppendLine($"// Function {func.SkillName}.{func.Name}.");
+ Console.WriteLine("{0}.{1} is missing a description", function.PluginName, function.Name);
+ list.AppendLine($"// Function {function.PluginName}.{function.Name}.");
}
// Function name
- list.AppendLine($"{func.SkillName}.{func.Name}");
+ list.AppendLine($"{function.PluginName}.{function.Name}");
// Function parameters
- foreach (var p in func.Parameters)
+ foreach (var p in function.Parameters)
{
var description = string.IsNullOrEmpty(p.Description) ? p.Name : p.Description;
var defaultValueString = string.IsNullOrEmpty(p.DefaultValue) ? string.Empty : $" (default value: {p.DefaultValue})";
list.AppendLine($"Parameter \"{p.Name}\": {description} {defaultValueString}");
}
- }
}
Console.WriteLine($"List of all skills ----- {list.ToString()}");
@@ -204,17 +198,9 @@ public class SemanticKernelSkill : CodeActivity<string>
string field = function.FieldType.ToString();
if (field.Equals("Microsoft.SKDevTeam.SemanticFunctionConfig"))
{
- var skillConfig = SemanticFunctionConfig.ForSkillAndFunction(skillType.Name, function.Name);
+ var prompt = Skills.ForSkillAndFunction(skillType.Name, function.Name);
var skfunc = kernel.CreateSemanticFunction(
- skillConfig.PromptTemplate,
- skillConfig.Name,
- skillConfig.SkillName,
- skillConfig.Description,
- skillConfig.MaxTokens,
- skillConfig.Temperature,
- skillConfig.TopP,
- skillConfig.PPenalty,
- skillConfig.FPenalty);
+ prompt, new OpenAIRequestSettings { MaxTokens = 8000, Temperature = 0.4, TopP = 1 });
Console.WriteLine($"SK Added function: {skfunc.SkillName}.{skfunc.Name}");
}
diff --git a/src/libs/Elsa.SemanticKernel/Elsa.SemanticKernel.csproj b/src/libs/Elsa.SemanticKernel/Elsa.SemanticKernel.csproj
index c6f821073..85445d758 100644
--- a/src/libs/Elsa.SemanticKernel/Elsa.SemanticKernel.csproj
+++ b/src/libs/Elsa.SemanticKernel/Elsa.SemanticKernel.csproj
@@ -21,8 +21,8 @@
<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.24.230918.1-preview" />
- <PackageReference Include="Microsoft.SemanticKernel.Connectors.Memory.Qdrant" Version="0.24.230918.1-preview" />
+ <PackageReference Include="Microsoft.SemanticKernel" Version="1.0.0-beta5" />
+ <PackageReference Include="Microsoft.SemanticKernel.Connectors.Memory.Qdrant" Version="1.0.0-beta5" />
<ProjectReference Include="..\Microsoft.AI.DevTeam.Skills\Microsoft.AI.DevTeam.Skills.csproj" />
</ItemGroup>
diff --git a/src/libs/Microsoft.AI.DevTeam.Skills/Chat.cs b/src/libs/Microsoft.AI.DevTeam.Skills/Chat.cs
deleted file mode 100644
index 2f192a723..000000000
--- a/src/libs/Microsoft.AI.DevTeam.Skills/Chat.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-namespace Microsoft.AI.DevTeam.Skills;
-public static class Chat
-{
- public static SemanticFunctionConfig ChatCompletion = new SemanticFunctionConfig
- {
- PromptTemplate = """
- You are a helpful assistant. Please complete the prompt as instructed in the Input.
- Provide as many references and links as needed to support the accuracy of your answer.
- Input: {{$input}}
- """,
- Name = nameof(ChatCompletion),
- SkillName = nameof(Chat),
- Description = "Use the Model as a Chatbot.",
- MaxTokens = 6500,
- Temperature = 0.0,
- TopP = 0.0,
- PPenalty = 0.0,
- FPenalty = 0.0
- };
-
-}
diff --git a/src/libs/Microsoft.AI.DevTeam.Skills/CodeExplainer.cs b/src/libs/Microsoft.AI.DevTeam.Skills/CodeExplainer.cs
deleted file mode 100644
index ffba6a71e..000000000
--- a/src/libs/Microsoft.AI.DevTeam.Skills/CodeExplainer.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-
-namespace Microsoft.AI.DevTeam.Skills;
-public static class CodeExplainer {
- public static SemanticFunctionConfig Explain = new SemanticFunctionConfig
- {
- PromptTemplate = """
- You are a Software Developer.
- Please explain the code that is in the input below. You can include references or documentation links in your explanation.
- Also where appropriate please output a list of keywords to describe the code or its capabilities.
- example:
- Keywords: Azure, networking, security, authentication
-
- If the code's purpose is not clear output an error:
- Error: The model could not determine the purpose of the code.
-
- --
- Input: {{$input}}
- """,
- Name = nameof(Explain),
- SkillName = nameof(CodeExplainer),
- Description = "From a description of a coding task out put the code or scripts necessary to complete the task.",
- MaxTokens = 6500,
- Temperature = 0.0,
- TopP = 0.0,
- PPenalty = 0.0,
- FPenalty = 0.0
- };
-
-}
diff --git a/src/libs/Microsoft.AI.DevTeam.Skills/DevLead.cs b/src/libs/Microsoft.AI.DevTeam.Skills/DevLead.cs
index e325af3df..a1c677bc1 100644
--- a/src/libs/Microsoft.AI.DevTeam.Skills/DevLead.cs
+++ b/src/libs/Microsoft.AI.DevTeam.Skills/DevLead.cs
@@ -1,8 +1,6 @@
namespace Microsoft.AI.DevTeam.Skills;
public static class DevLead {
- public static SemanticFunctionConfig Plan = new SemanticFunctionConfig
- {
- PromptTemplate = """
+ public static string Plan = """
You are a Dev Lead for an application team, building the application described below.
Please break down the steps and modules required to develop the complete application, describe each step in detail.
Make prescriptive architecture, language, and frameowrk choices, do not provide a range of choices.
@@ -34,14 +32,19 @@ public static class DevLead {
Do not output any other text.
Input: {{$input}}
{{$wafContext}}
- """,
- Name = nameof(Plan),
- SkillName = nameof(DevLead),
- Description = "From a simple description of an application output a development plan for building the application.",
- MaxTokens = 6500,
- Temperature = 0.0,
- TopP = 0.0,
- PPenalty = 0.0,
- FPenalty = 0.0
- };
+ """;
+
+ public static string Explain = """
+ You are a Dev Lead.
+ Please explain the code that is in the input below. You can include references or documentation links in your explanation.
+ Also where appropriate please output a list of keywords to describe the code or its capabilities.
+ example:
+ Keywords: Azure, networking, security, authentication
+
+ If the code's purpose is not clear output an error:
+ Error: The model could not determine the purpose of the code.
+
+ --
+ Input: {{$input}}
+ """;
}
diff --git a/src/libs/Microsoft.AI.DevTeam.Skills/Developer.cs b/src/libs/Microsoft.AI.DevTeam.Skills/Developer.cs
index 9a1db00d6..54cfb0dc8 100644
--- a/src/libs/Microsoft.AI.DevTeam.Skills/Developer.cs
+++ b/src/libs/Microsoft.AI.DevTeam.Skills/Developer.cs
@@ -1,9 +1,7 @@
namespace Microsoft.AI.DevTeam.Skills;
public static class Developer {
- public static SemanticFunctionConfig Implement = new SemanticFunctionConfig
- {
- PromptTemplate = """
+ public static string Implement = """
You are a Developer for an application.
Please output the code required to accomplish the task assigned to you below and wrap it in a bash script that creates the files.
Do not use any IDE commands and do not build and run the code.
@@ -11,20 +9,9 @@ public static class Developer {
Use comments in the code to describe the intent. Do not include other text other than code and code comments.
Input: {{$input}}
{{$wafContext}}
- """,
- Name = nameof(Implement),
- SkillName = nameof(Developer),
- Description = "From a description of a coding task out put the code or scripts necessary to complete the task.",
- MaxTokens = 6500,
- Temperature = 0.0,
- TopP = 0.0,
- PPenalty = 0.0,
- FPenalty = 0.0
- };
+ """;
- public static SemanticFunctionConfig Improve = new SemanticFunctionConfig
- {
- PromptTemplate = """
+ public static string Improve = """
You are a Developer for an application. Your job is to imrove the code that you are given in the input below.
Please output a new version of code that fixes any problems with this version.
If there is an error message in the input you should fix that error in the code.
@@ -34,14 +21,36 @@ public static class Developer {
Use comments in the code to describe the intent. Do not include other text other than code and code comments.
Input: {{$input}}
{{$wafContext}}
- """,
- Name = nameof(Improve),
- SkillName = nameof(Developer),
- Description = "From a description of a coding task out put the code or scripts necessary to complete the task.",
- MaxTokens = 6500,
- Temperature = 0.0,
- TopP = 0.0,
- PPenalty = 0.0,
- FPenalty = 0.0
- };
-}
+ """;
+
+ public static string Explain = """
+ You are an experienced software developer, with strong experience in Azure and Microsoft technologies.
+ Extract the key features and capabilities of the code file below, with the intent to build an understanding of an entire code repository.
+ You can include references or documentation links in your explanation. Also where appropriate please output a list of keywords to describe the code or its capabilities.
+ Example:
+ Keywords: Azure, networking, security, authentication
+
+ ===code===
+ {{$input}}
+ ===end-code===
+ Only include the points in a bullet point format and DON'T add anything outside of the bulleted list.
+ Be short and concise.
+ If the code's purpose is not clear output an error:
+ Error: The model could not determine the purpose of the code.
+ """;
+
+ public static string ConsolidateUnderstanding = """
+ You are an experienced software developer, with strong experience in Azure and Microsoft technologies.
+ You are trying to build an understanding of the codebase from code files. This is the current understanding of the project:
+ ===current-understanding===
+ {{$input}}
+ ===end-current-understanding===
+ and this is the new information that surfaced
+ ===new-understanding===
+ {{$newUnderstanding}}
+ ===end-new-understanding===
+ Your job is to update your current understanding with the new information.
+ Only include the points in a bullet point format and DON'T add anything outside of the bulleted list.
+ Be short and concise.
+ """;
+}
\ No newline at end of file
diff --git a/src/libs/Microsoft.AI.DevTeam.Skills/Extensions.cs b/src/libs/Microsoft.AI.DevTeam.Skills/Extensions.cs
new file mode 100644
index 000000000..b77b45813
--- /dev/null
+++ b/src/libs/Microsoft.AI.DevTeam.Skills/Extensions.cs
@@ -0,0 +1,24 @@
+namespace Microsoft.AI.DevTeam.Skills;
+
+public static class Skills
+{
+ public static string ForSkillAndFunction(string skillName, string functionName) =>
+ (skillName, functionName) switch
+ {
+ (nameof(PM), nameof(PM.BootstrapProject)) => PM.BootstrapProject,
+ (nameof(PM), nameof(PM.Readme)) => PM.Readme,
+ (nameof(DevLead), nameof(DevLead.Plan)) => DevLead.Plan,
+ (nameof(Developer), nameof(Developer.Implement)) => Developer.Implement,
+ (nameof(Developer), nameof(Developer.Improve)) => Developer.Improve,
+ _ => throw new ArgumentException($"Unable to find {skillName}.{functionName}")
+ };
+}
+
+public interface IFunction
+{
+ string Name { get; }
+ string Description { get; }
+ string PluginName { get; }
+ string DefaultValue { get; }
+ string[] Parameters { get; }
+}
diff --git a/src/libs/Microsoft.AI.DevTeam.Skills/Microsoft.AI.DevTeam.Skills.csproj b/src/libs/Microsoft.AI.DevTeam.Skills/Microsoft.AI.DevTeam.Skills.csproj
index 11eebbb3e..fb2eeb6a7 100644
--- a/src/libs/Microsoft.AI.DevTeam.Skills/Microsoft.AI.DevTeam.Skills.csproj
+++ b/src/libs/Microsoft.AI.DevTeam.Skills/Microsoft.AI.DevTeam.Skills.csproj
@@ -7,6 +7,6 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.SemanticKernel" Version="0.24.230918.1-preview" />
+ <PackageReference Include="Microsoft.SemanticKernel" Version="1.0.0-beta5" />
</ItemGroup>
</Project>
diff --git a/src/libs/Microsoft.AI.DevTeam.Skills/PM.cs b/src/libs/Microsoft.AI.DevTeam.Skills/PM.cs
index dd4dcb247..0ec71b782 100644
--- a/src/libs/Microsoft.AI.DevTeam.Skills/PM.cs
+++ b/src/libs/Microsoft.AI.DevTeam.Skills/PM.cs
@@ -1,42 +1,34 @@
namespace Microsoft.AI.DevTeam.Skills;
public static class PM
{
- public static SemanticFunctionConfig BootstrapProject = new SemanticFunctionConfig
- {
- PromptTemplate = """
+public static string BootstrapProject = """
Please write a bash script with the commands that would be required to generate applications as described in the following input.
You may add comments to the script and the generated output but do not add any other text except the bash script.
You may include commands to build the applications but do not run them.
Do not include any git commands.
Input: {{$input}}
{{$wafContext}}
- """,
- Name = nameof(BootstrapProject),
- SkillName = nameof(PM),
- Description = "Bootstrap a new project",
- MaxTokens = 6500,
- Temperature = 0.0,
- TopP = 0.0,
- PPenalty = 0.0,
- FPenalty = 0.0
- };
- public static SemanticFunctionConfig Readme = new SemanticFunctionConfig
- {
- PromptTemplate = """
+ """;
+ public static string Readme = """
You are a program manager on a software development team. You are working on an app described below.
Based on the input below, and any dialog or other context, please output a raw README.MD markdown file documenting the main features of the app and the architecture or code organization.
Do not describe how to create the application.
Write the README as if it were documenting the features and architecture of the application. You may include instructions for how to run the application.
Input: {{$input}}
{{$wafContext}}
- """,
- Name = nameof(Readme),
- SkillName = nameof(PM),
- Description = "From a simple description output a README.md file for a GitHub repository.",
- MaxTokens = 6500,
- Temperature = 0.0,
- TopP = 0.0,
- PPenalty = 0.0,
- FPenalty = 0.0
- };
+ """;
+
+ public static string Explain = """
+ You are a Product Manager.
+ Please explain the code that is in the input below. You can include references or documentation links in your explanation.
+ Also where appropriate please output a list of keywords to describe the code or its capabilities.
+ example:
+ Keywords: Azure, networking, security, authentication
+
+ If the code's purpose is not clear output an error:
+ Error: The model could not determine the purpose of the code.
+
+ --
+ Input: {{$input}}
+ """;
}
diff --git a/src/libs/Microsoft.AI.DevTeam.Skills/SemanticFunctionConfig.cs b/src/libs/Microsoft.AI.DevTeam.Skills/SemanticFunctionConfig.cs
deleted file mode 100644
index 17a7ec8c3..000000000
--- a/src/libs/Microsoft.AI.DevTeam.Skills/SemanticFunctionConfig.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-using Microsoft.SemanticKernel;
-using Microsoft.SemanticKernel.SkillDefinition;
-
-namespace Microsoft.AI.DevTeam.Skills;
-
-public class SemanticFunctionConfig
-{
- public string PromptTemplate { get; set; }
- public string Name { get; set; }
- public string SkillName { get; set; }
- public string Description { get; set; }
- public int MaxTokens { get; set; }
- public double Temperature { get; set; }
- public double TopP { get; set; }
- public double PPenalty { get; set; }
- public double FPenalty { get; set; }
- public static SemanticFunctionConfig ForSkillAndFunction(string skillName, string functionName) =>
- (skillName, functionName) switch
- {
- (nameof(Chat), nameof(Chat.ChatCompletion)) => Chat.ChatCompletion,
- (nameof(PM), nameof(PM.BootstrapProject)) => PM.BootstrapProject,
- (nameof(PM), nameof(PM.Readme)) => PM.Readme,
- (nameof(DevLead), nameof(DevLead.Plan)) => DevLead.Plan,
- (nameof(CodeExplainer), nameof(CodeExplainer.Explain)) => CodeExplainer.Explain,
- (nameof(Developer), nameof(Developer.Implement)) => Developer.Implement,
- (nameof(Developer), nameof(Developer.Improve)) => Developer.Improve,
- _ => throw new ArgumentException($"Unable to find {skillName}.{functionName}")
- };
-}
-
-public static class SemanticKernelExtensions
-{
- public static ISKFunction LoadFunction(this IKernel kernel, string skill, string function)
- {
- var skillConfig = SemanticFunctionConfig.ForSkillAndFunction(skill, function);
- return kernel.CreateSemanticFunction(skillConfig.PromptTemplate, skillConfig.Name, skillConfig.SkillName,
- skillConfig.Description, skillConfig.MaxTokens, skillConfig.Temperature,
- skillConfig.TopP, skillConfig.PPenalty, skillConfig.FPenalty);
- }
-}
\ No newline at end of file
diff --git a/src/libs/Microsoft.AI.DevTeam/Actors/Architect/Architect.cs b/src/libs/Microsoft.AI.DevTeam/Actors/Architect/Architect.cs
index 9b91239cf..24a421e90 100644
--- a/src/libs/Microsoft.AI.DevTeam/Actors/Architect/Architect.cs
+++ b/src/libs/Microsoft.AI.DevTeam/Actors/Architect/Architect.cs
@@ -4,7 +4,7 @@ namespace Microsoft.AI.DevTeam;
public class Architect : SemanticPersona, IArchitectSolutions
{
- public Architect( [PersistentState("state", "messages")]IPersistentState<ChatHistory> state) : base(state)
+ public Architect( [PersistentState("state", "messages")]IPersistentState<SemanticPersonaState> state) : base(state)
{
}
diff --git a/src/libs/Microsoft.AI.DevTeam/Actors/Conductor/Conductor.cs b/src/libs/Microsoft.AI.DevTeam/Actors/Conductor/Conductor.cs
index 664e6b3ab..51c05b88d 100644
--- a/src/libs/Microsoft.AI.DevTeam/Actors/Conductor/Conductor.cs
+++ b/src/libs/Microsoft.AI.DevTeam/Actors/Conductor/Conductor.cs
@@ -37,8 +37,6 @@ public class Conductor : Grain, IOrchestrateWorkflows
ParentNumber = parentNumber
});
var suffix = $"{org}-{repo}";
- var pm = GrainFactory.GetGrain<IManageProduct>(pmIssue.IssueNumber, suffix);
- var devLead = GrainFactory.GetGrain<ILeadDevelopment>(devLeadIssue.IssueNumber, suffix);
var lookup = GrainFactory.GetGrain<ILookupMetadata>(suffix);
var metadataList = new List<StoreMetadataPairs>{
@@ -81,9 +79,4 @@ public class Conductor : Grain, IOrchestrateWorkflows
}
await lookup.StoreMetadata(metadataList);
}
-
- public Task ScheduleCommitSandboxRun(CommitRequest commitRequest, MarkTaskCompleteRequest markTaskCompleteRequest)
- {
- throw new NotImplementedException();
- }
}
diff --git a/src/libs/Microsoft.AI.DevTeam/Actors/DevLead/DeveloperLead.cs b/src/libs/Microsoft.AI.DevTeam/Actors/DevLead/DeveloperLead.cs
index d7755d791..bad46c0bb 100644
--- a/src/libs/Microsoft.AI.DevTeam/Actors/DevLead/DeveloperLead.cs
+++ b/src/libs/Microsoft.AI.DevTeam/Actors/DevLead/DeveloperLead.cs
@@ -1,5 +1,8 @@
using Microsoft.AI.DevTeam.Skills;
+using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
+using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
+using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Orchestration;
using Orleans.Runtime;
using System.Text.Json;
@@ -8,44 +11,51 @@ namespace Microsoft.AI.DevTeam;
public class DeveloperLead : SemanticPersona, ILeadDevelopment
{
private readonly IKernel _kernel;
+ private readonly ISemanticTextMemory _memory;
+ private readonly ILogger<DeveloperLead> _logger;
+
protected override string MemorySegment => "dev-lead-memory";
- public DeveloperLead(IKernel kernel, [PersistentState("state", "messages")] IPersistentState<ChatHistory> state) : base(state)
+ public DeveloperLead([PersistentState("state", "messages")] IPersistentState<SemanticPersonaState> state,IKernel kernel, ISemanticTextMemory memory, ILogger<DeveloperLead> logger) : base(state)
{
_kernel = kernel;
+ _memory = memory;
+ _logger = logger;
}
public async Task<string> CreatePlan(string ask)
{
- // var architectId = Guid.NewGuid();
- // var plan = "this is my plan";
- // var architect = GrainFactory.GetGrain<IArchitectSolutions>(architectId);
- // var review = architect.ReviewPlan(plan);
- // return Task.FromResult(plan);
-
- var function = _kernel.LoadFunction(nameof(DevLead), nameof(DevLead.Plan));
- var context = new ContextVariables();
- context.Set("input", ask);
- if (_state.State.History == null) _state.State.History = new List<ChatHistoryItem>();
- _state.State.History.Add(new ChatHistoryItem
+ try
{
- Message = ask,
- Order = _state.State.History.Count + 1,
- UserType = ChatUserType.User
- });
- await AddWafContext(_kernel, ask, context);
- context.Set("input", ask);
+ var function = _kernel.CreateSemanticFunction(DevLead.Plan, new OpenAIRequestSettings { MaxTokens = 15000, Temperature = 0.4, TopP = 1 });
+ var context = new ContextVariables();
+ context.Set("input", ask);
+ if (_state.State.History == null) _state.State.History = new List<ChatHistoryItem>();
+ _state.State.History.Add(new ChatHistoryItem
+ {
+ Message = ask,
+ Order = _state.State.History.Count + 1,
+ UserType = ChatUserType.User
+ });
+ await AddWafContext(_memory, ask, context);
+ context.Set("input", ask);
- var result = await _kernel.RunAsync(context, function);
- var resultMessage = result.ToString();
- _state.State.History.Add(new ChatHistoryItem
+ var result = await _kernel.RunAsync(context, function);
+ var resultMessage = result.ToString();
+ _state.State.History.Add(new ChatHistoryItem
+ {
+ Message = resultMessage,
+ Order = _state.State.History.Count + 1,
+ UserType = ChatUserType.Agent
+ });
+ await _state.WriteStateAsync();
+
+ return resultMessage;
+ }
+ catch (Exception ex)
{
- Message = resultMessage,
- Order = _state.State.History.Count + 1,
- UserType = ChatUserType.Agent
- });
- await _state.WriteStateAsync();
-
- return resultMessage;
+ _logger.LogError(ex, "Error creating development plan");
+ return default;
+ }
}
public Task<DevLeadPlanResponse> GetLatestPlan()
diff --git a/src/libs/Microsoft.AI.DevTeam/Actors/Developer/Developer.cs b/src/libs/Microsoft.AI.DevTeam/Actors/Developer/Developer.cs
index 5991196c9..b54a60476 100644
--- a/src/libs/Microsoft.AI.DevTeam/Actors/Developer/Developer.cs
+++ b/src/libs/Microsoft.AI.DevTeam/Actors/Developer/Developer.cs
@@ -1,5 +1,8 @@
using Microsoft.AI.DevTeam.Skills;
+using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
+using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
+using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Orchestration;
using Orleans.Runtime;
@@ -8,44 +11,91 @@ namespace Microsoft.AI.DevTeam;
public class Dev : SemanticPersona, IDevelopCode
{
private readonly IKernel _kernel;
- protected override string MemorySegment => "dev-memory";
+ private readonly ISemanticTextMemory _memory;
+ private readonly ILogger<Dev> _logger;
- public Dev(IKernel kernel, [PersistentState("state", "messages")]IPersistentState<ChatHistory> state) : base(state)
+ protected override string MemorySegment => "dev-memory";
+
+ public Dev([PersistentState("state", "messages")] IPersistentState<SemanticPersonaState> state, IKernel kernel, ISemanticTextMemory memory, ILogger<Dev> logger) : base(state)
{
_kernel = kernel;
+ _memory = memory;
+ _logger = logger;
}
public async Task<string> GenerateCode(string ask)
{
- var function = _kernel.LoadFunction(nameof(Developer), nameof(Developer.Implement));
- var context = new ContextVariables();
- if (_state.State.History == null) _state.State.History = new List<ChatHistoryItem>();
- _state.State.History.Add(new ChatHistoryItem
- {
- Message = ask,
- Order = _state.State.History.Count + 1,
- UserType = ChatUserType.User
- });
- await AddWafContext(_kernel, ask, context);
- context.Set("input", ask);
-
- var result = await _kernel.RunAsync(context, function);
- var resultMessage = result.ToString();
- _state.State.History.Add(new ChatHistoryItem
+ try
{
- Message = resultMessage,
- Order = _state.State.History.Count + 1,
- UserType = ChatUserType.Agent
- });
- await _state.WriteStateAsync();
+ var function = _kernel.CreateSemanticFunction(Developer.Implement, new OpenAIRequestSettings { MaxTokens = 15000, Temperature = 0.8, TopP = 1 });
+ var context = new ContextVariables();
+ if (_state.State.History == null) _state.State.History = new List<ChatHistoryItem>();
+ _state.State.History.Add(new ChatHistoryItem
+ {
+ Message = ask,
+ Order = _state.State.History.Count + 1,
+ UserType = ChatUserType.User
+ });
+ await AddWafContext(_memory, ask, context);
+ context.Set("input", ask);
- return resultMessage;
+ var result = await _kernel.RunAsync(context, function);
+ var resultMessage = result.ToString();
+ _state.State.History.Add(new ChatHistoryItem
+ {
+ Message = resultMessage,
+ Order = _state.State.History.Count + 1,
+ UserType = ChatUserType.Agent
+ });
+ await _state.WriteStateAsync();
+
+ return resultMessage;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error generating code");
+ return default;
+ }
}
-
+
public Task<string> ReviewPlan(string plan)
{
throw new NotImplementedException();
}
-}
+
+ public async Task<UnderstandingResult> BuildUnderstanding(string content)
+ {
+ try
+ {
+ var explainFunction = _kernel.CreateSemanticFunction(Developer.Explain, new OpenAIRequestSettings { MaxTokens = 15000, Temperature = 0.8, TopP = 1 });
+ var consolidateFunction = _kernel.CreateSemanticFunction(Developer.ConsolidateUnderstanding, new OpenAIRequestSettings { MaxTokens = 15000, Temperature = 0.8, TopP = 1 });
+ var explainContext = new ContextVariables();
+ explainContext.Set("input", content);
+ var explainResult = await _kernel.RunAsync(explainContext, explainFunction);
+ var explainMesage = explainResult.ToString();
+
+ var consolidateContext = new ContextVariables();
+ consolidateContext.Set("input", _state.State.Understanding);
+ consolidateContext.Set("newUnderstanding", explainMesage);
+
+ var consolidateResult = await _kernel.RunAsync(consolidateContext, consolidateFunction);
+ var consolidateMessage = consolidateResult.ToString();
+
+ _state.State.Understanding = consolidateMessage;
+ await _state.WriteStateAsync();
+
+ return new UnderstandingResult
+ {
+ NewUnderstanding = consolidateMessage,
+ Explanation = explainMesage
+ };
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error building understanding");
+ return default;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/libs/Microsoft.AI.DevTeam/Actors/Developer/IDevelopCode.cs b/src/libs/Microsoft.AI.DevTeam/Actors/Developer/IDevelopCode.cs
index 027fa0878..e35ad7146 100644
--- a/src/libs/Microsoft.AI.DevTeam/Actors/Developer/IDevelopCode.cs
+++ b/src/libs/Microsoft.AI.DevTeam/Actors/Developer/IDevelopCode.cs
@@ -1,6 +1,6 @@
namespace Microsoft.AI.DevTeam;
-public interface IDevelopCode : IGrainWithIntegerCompoundKey, IChatHistory
+public interface IDevelopCode : IGrainWithIntegerCompoundKey, IChatHistory, IUnderstand
{
Task<string> GenerateCode(string ask);
Task<string> ReviewPlan(string plan);
diff --git a/src/libs/Microsoft.AI.DevTeam/Actors/Ingester/Ingester.cs b/src/libs/Microsoft.AI.DevTeam/Actors/Ingester/Ingester.cs
index 3952bbf33..74faa6be4 100644
--- a/src/libs/Microsoft.AI.DevTeam/Actors/Ingester/Ingester.cs
+++ b/src/libs/Microsoft.AI.DevTeam/Actors/Ingester/Ingester.cs
@@ -1,4 +1,5 @@
using Microsoft.SemanticKernel;
+using Microsoft.SemanticKernel.Memory;
using Octokit;
using Orleans.Runtime;
@@ -9,24 +10,32 @@ public class Ingester : SemanticPersona, IIngestRepo
protected override string MemorySegment => "code-analysis";
private readonly IManageGithub _ghService;
private readonly IKernel _kernel;
+ private readonly ISemanticTextMemory _memory;
private readonly IAnalyzeCode _codeAnalyzer;
- public Ingester([PersistentState("state", "messages")] IPersistentState<ChatHistory> state, IManageGithub ghService, IKernel kernel, IAnalyzeCode codeAnalyzer) : base(state)
+ public Ingester([PersistentState("state", "messages")] IPersistentState<SemanticPersonaState> state, IManageGithub ghService, IKernel kernel, ISemanticTextMemory memory, IAnalyzeCode codeAnalyzer) : base(state)
{
_ghService = ghService;
_kernel = kernel;
+ _memory = memory;
_codeAnalyzer = codeAnalyzer;
}
public async Task IngestionFlow(string org, string repo, string branch)
{
+ var suffix = $"{org}-{repo}";
var language = await _ghService.GetMainLanguage(org, repo);
var files = await _ghService.GetFiles(org, repo, branch, Language.Filters[language]);
+
+ var dev = GrainFactory.GetGrain<IDevelopCode>(0, suffix);
+
foreach (var file in files)
{
var codeAnalysis = await _codeAnalyzer.Analyze(file.Content);
- codeAnalysis.ToList()
- .ForEach(async c =>
- await _kernel.Memory.SaveInformationAsync(MemorySegment, c.CodeBlock, Guid.NewGuid().ToString(), c.Meaning));
+ codeAnalysis.ToList().ForEach(async c =>
+ await _memory.SaveInformationAsync(MemorySegment, c.CodeBlock, Guid.NewGuid().ToString(), c.Meaning));
+
+ // TODO: do something with the result
+ await dev.BuildUnderstanding(file.Content);
}
}
}
diff --git a/src/libs/Microsoft.AI.DevTeam/Actors/ProductManager/ProductManager.cs b/src/libs/Microsoft.AI.DevTeam/Actors/ProductManager/ProductManager.cs
index 4f4bde3ca..231f24351 100644
--- a/src/libs/Microsoft.AI.DevTeam/Actors/ProductManager/ProductManager.cs
+++ b/src/libs/Microsoft.AI.DevTeam/Actors/ProductManager/ProductManager.cs
@@ -1,5 +1,8 @@
using Microsoft.AI.DevTeam.Skills;
+using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
+using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
+using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Orchestration;
using Orleans.Runtime;
@@ -7,36 +10,49 @@ namespace Microsoft.AI.DevTeam;
public class ProductManager : SemanticPersona, IManageProduct
{
private readonly IKernel _kernel;
+ private readonly ISemanticTextMemory _memory;
+ private readonly ILogger<ProductManager> _logger;
+
protected override string MemorySegment => "pm-memory";
- public ProductManager(IKernel kernel,[PersistentState("state", "messages")] IPersistentState<ChatHistory> state) : base(state)
+ public ProductManager([PersistentState("state", "messages")] IPersistentState<SemanticPersonaState> state, IKernel kernel, ISemanticTextMemory memory, ILogger<ProductManager> logger) : base(state)
{
_kernel = kernel;
+ _memory = memory;
+ _logger = logger;
}
public async Task<string> CreateReadme(string ask)
{
- var function = _kernel.LoadFunction(nameof(PM), nameof(PM.Readme));
- var context = new ContextVariables();
- context.Set("input", ask);
- if(_state.State.History == null) _state.State.History = new List<ChatHistoryItem>();
- _state.State.History.Add(new ChatHistoryItem
+ try
{
- Message = ask,
- Order = _state.State.History.Count + 1,
- UserType = ChatUserType.User
- });
- await AddWafContext(_kernel, ask, context);
- context.Set("input", ask);
+ var function = _kernel.CreateSemanticFunction(PM.Readme, new OpenAIRequestSettings { MaxTokens = 10000, Temperature = 0.6, TopP = 1 });
+ var context = new ContextVariables();
+ context.Set("input", ask);
+ if (_state.State.History == null) _state.State.History = new List<ChatHistoryItem>();
+ _state.State.History.Add(new ChatHistoryItem
+ {
+ Message = ask,
+ Order = _state.State.History.Count + 1,
+ UserType = ChatUserType.User
+ });
+ await AddWafContext(_memory, ask, context);
+ context.Set("input", ask);
- var result = await _kernel.RunAsync(context, function);
- var resultMessage = result.ToString();
- _state.State.History.Add(new ChatHistoryItem
+ var result = await _kernel.RunAsync(context, function);
+ var resultMessage = result.ToString();
+ _state.State.History.Add(new ChatHistoryItem
+ {
+ Message = resultMessage,
+ Order = _state.State.History.Count + 1,
+ UserType = ChatUserType.Agent
+ });
+ await _state.WriteStateAsync();
+ return resultMessage;
+ }
+ catch (Exception ex)
{
- Message = resultMessage,
- Order = _state.State.History.Count + 1,
- UserType = ChatUserType.Agent
- });
- await _state.WriteStateAsync();
- return resultMessage;
+ _logger.LogError(ex, "Error creating readme");
+ return default;
+ }
}
}
diff --git a/src/libs/Microsoft.AI.DevTeam/Actors/SemanticPersona.cs b/src/libs/Microsoft.AI.DevTeam/Actors/SemanticPersona.cs
index 1ae539ad8..340e06798 100644
--- a/src/libs/Microsoft.AI.DevTeam/Actors/SemanticPersona.cs
+++ b/src/libs/Microsoft.AI.DevTeam/Actors/SemanticPersona.cs
@@ -1,4 +1,5 @@
using Microsoft.SemanticKernel;
+using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Orchestration;
using Orleans.Runtime;
@@ -7,26 +8,26 @@ namespace Microsoft.AI.DevTeam;
public abstract class SemanticPersona : Grain, IChatHistory
{
public SemanticPersona(
- [PersistentState("state", "messages")] IPersistentState<ChatHistory> state)
+ [PersistentState("state", "messages")] IPersistentState<SemanticPersonaState> state)
{
_state = state;
}
protected virtual string MemorySegment { get; set; }
protected List<ChatHistoryItem> History { get; set; }
- protected readonly IPersistentState<ChatHistory> _state;
+ protected readonly IPersistentState<SemanticPersonaState> _state;
public async Task<string> GetLastMessage()
{
return _state.State.History.Last().Message;
}
- protected async Task AddWafContext(IKernel kernel, string ask, ContextVariables context)
+ protected async Task AddWafContext(ISemanticTextMemory memory, string ask, ContextVariables context)
{
- var interestingMemories = kernel.Memory.SearchAsync("waf-pages", ask, 2);
+ var interestingMemories = memory.SearchAsync("waf-pages", ask, 2);
var wafContext = "Consider the following architectural guidelines:";
- await foreach (var memory in interestingMemories)
+ await foreach (var m in interestingMemories)
{
- wafContext += $"\n {memory.Metadata.Text}";
+ wafContext += $"\n {m.Metadata.Text}";
}
context.Set("wafContext", wafContext);
@@ -38,6 +39,18 @@ public interface IChatHistory
Task<string> GetLastMessage();
}
+public interface IUnderstand
+{
+ Task<UnderstandingResult> BuildUnderstanding(string content);
+}
+
+[GenerateSerializer]
+public class UnderstandingResult {
+ [Id(0)]
+ public string NewUnderstanding { get; set; }
+ [Id(1)]
+ public string Explanation { get; set; }
+}
[Serializable]
public class ChatHistoryItem
@@ -48,9 +61,10 @@ public class ChatHistoryItem
}
-public class ChatHistory
+public class SemanticPersonaState
{
public List<ChatHistoryItem> History { get; set; }
+ public string Understanding { get; set; }
}
public enum ChatUserType
diff --git a/src/libs/Microsoft.AI.DevTeam/Actors/Tester/Tester.cs b/src/libs/Microsoft.AI.DevTeam/Actors/Tester/Tester.cs
index e44abac9b..cb9fcad2a 100644
--- a/src/libs/Microsoft.AI.DevTeam/Actors/Tester/Tester.cs
+++ b/src/libs/Microsoft.AI.DevTeam/Actors/Tester/Tester.cs
@@ -5,7 +5,7 @@ namespace Microsoft.AI.DevTeam;
public class Tester : SemanticPersona, ITestCode
{
public Tester(
- [PersistentState("state", "messages")]IPersistentState<ChatHistory> state) : base(state)
+ [PersistentState("state", "messages")]IPersistentState<SemanticPersonaState> state) : base(state)
{
}
diff --git a/src/libs/Microsoft.AI.DevTeam/Microsoft.AI.DevTeam.csproj b/src/libs/Microsoft.AI.DevTeam/Microsoft.AI.DevTeam.csproj
index b3c2a1dd6..4e767065d 100644
--- a/src/libs/Microsoft.AI.DevTeam/Microsoft.AI.DevTeam.csproj
+++ b/src/libs/Microsoft.AI.DevTeam/Microsoft.AI.DevTeam.csproj
@@ -10,7 +10,7 @@
<PackageReference Include="Microsoft.Orleans.Sdk" Version="7.2.1" />
<PackageReference Include="Microsoft.Orleans.Runtime" Version="7.2.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
- <PackageReference Include="Microsoft.SemanticKernel" Version="0.24.230918.1-preview" />
+ <PackageReference Include="Microsoft.SemanticKernel" Version="1.0.0-beta5" />
<PackageReference Include="Octokit" Version="7.1.0" />
<PackageReference Include="GitHubJwt" Version="0.0.6" />
<PackageReference Include="Azure.ResourceManager.ContainerInstance" Version="1.2.0-beta.1" />
diff --git a/src/libs/Microsoft.AI.DevTeam/Services/AzureService.cs b/src/libs/Microsoft.AI.DevTeam/Services/AzureService.cs
index 5326c285e..17229fea7 100644
--- a/src/libs/Microsoft.AI.DevTeam/Services/AzureService.cs
+++ b/src/libs/Microsoft.AI.DevTeam/Services/AzureService.cs
@@ -7,6 +7,7 @@ using Azure.ResourceManager.ContainerInstance;
using Azure.ResourceManager.ContainerInstance.Models;
using Azure.ResourceManager.Resources;
using Azure.Storage.Files.Shares;
+using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -15,108 +16,142 @@ namespace Microsoft.AI.DevTeam;
public class AzureService : IManageAzure
{
private readonly AzureOptions _azSettings;
+ private readonly ILogger<AzureService> _logger;
- public AzureService(IOptions<AzureOptions> azOptions)
+ public AzureService(IOptions<AzureOptions> azOptions, ILogger<AzureService> logger)
{
_azSettings = azOptions.Value;
+ _logger = logger;
}
public async Task DeleteSandbox(string sandboxId)
{
- var client = new ArmClient(new DefaultAzureCredential());
- var resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(_azSettings.SubscriptionId, _azSettings.ContainerInstancesResourceGroup);
- var resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
+ try
+ {
+ var client = new ArmClient(new DefaultAzureCredential());
+ var resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(_azSettings.SubscriptionId, _azSettings.ContainerInstancesResourceGroup);
+ var resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
+
+ var collection = resourceGroupResource.GetContainerGroups();
+ var containerGroup = await collection.GetAsync(sandboxId);
+ await containerGroup.Value.DeleteAsync(WaitUntil.Started);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error deleting sandbox");
+ }
- var collection = resourceGroupResource.GetContainerGroups();
- var containerGroup = await collection.GetAsync(sandboxId);
- await containerGroup.Value.DeleteAsync(WaitUntil.Started);
}
public async Task<bool> IsSandboxCompleted(string sandboxId)
{
- var client = new ArmClient(new DefaultAzureCredential());
- var resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(_azSettings.SubscriptionId, _azSettings.ContainerInstancesResourceGroup);
- var resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
-
- var collection = resourceGroupResource.GetContainerGroups();
- var containerGroup = await collection.GetAsync(sandboxId);
- return containerGroup.Value.Data.ProvisioningState == "Succeeded"
- && containerGroup.Value.Data.Containers.First().InstanceView.CurrentState.State == "Terminated";
+ try
+ {
+ var client = new ArmClient(new DefaultAzureCredential());
+ var resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(_azSettings.SubscriptionId, _azSettings.ContainerInstancesResourceGroup);
+ var resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
+
+ var collection = resourceGroupResource.GetContainerGroups();
+ var containerGroup = await collection.GetAsync(sandboxId);
+ return containerGroup.Value.Data.ProvisioningState == "Succeeded"
+ && containerGroup.Value.Data.Containers.First().InstanceView.CurrentState.State == "Terminated";
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error checking sandbox status");
+ return false;
+ }
}
public async Task RunInSandbox(SandboxRequest request)
{
- var client = string.IsNullOrEmpty(_azSettings.ManagedIdentity) ?
+ try
+ {
+ var client = string.IsNullOrEmpty(_azSettings.ManagedIdentity) ?
new ArmClient(new AzureCliCredential())
: new ArmClient(new ManagedIdentityCredential(_azSettings.ManagedIdentity));
- var runId = $"sk-sandbox-{request.Org}-{request.Repo}-{request.ParentIssueNumber}-{request.IssueNumber}";
- var resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(_azSettings.SubscriptionId, _azSettings.ContainerInstancesResourceGroup);
- var resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
- var scriptPath = $"/azfiles/output/{request.Org}-{request.Repo}/{request.ParentIssueNumber}/{request.IssueNumber}/run.sh";
- var collection = resourceGroupResource.GetContainerGroups();
- var data = new ContainerGroupData(new AzureLocation(_azSettings.Location), new ContainerInstanceContainer[]
- {
- new ContainerInstanceContainer(runId,_azSettings.SandboxImage,new ContainerResourceRequirements(new ContainerResourceRequestsContent(1.5,1)))
- {
- Command = { "/bin/bash", $"{scriptPath}" },
- VolumeMounts =
+ var runId = $"sk-sandbox-{request.Org}-{request.Repo}-{request.ParentIssueNumber}-{request.IssueNumber}";
+ var resourceGroupResourceId = ResourceGroupResource.CreateResourceIdentifier(_azSettings.SubscriptionId, _azSettings.ContainerInstancesResourceGroup);
+ var resourceGroupResource = client.GetResourceGroupResource(resourceGroupResourceId);
+ var scriptPath = $"/azfiles/output/{request.Org}-{request.Repo}/{request.ParentIssueNumber}/{request.IssueNumber}/run.sh";
+ var collection = resourceGroupResource.GetContainerGroups();
+ var data = new ContainerGroupData(new AzureLocation(_azSettings.Location), new ContainerInstanceContainer[]
+ {
+ new ContainerInstanceContainer(runId,_azSettings.SandboxImage,new ContainerResourceRequirements(new ContainerResourceRequestsContent(1.5,1)))
{
- new ContainerVolumeMount("azfiles","/azfiles/")
+ Command = { "/bin/bash", $"{scriptPath}" },
+ VolumeMounts =
{
- IsReadOnly = false,
- }
- },
- }}, ContainerInstanceOperatingSystemType.Linux)
- {
- Volumes =
- {
- new ContainerVolume("azfiles")
+ new ContainerVolumeMount("azfiles","/azfiles/")
+ {
+ IsReadOnly = false,
+ }
+ },
+ }}, ContainerInstanceOperatingSystemType.Linux)
+ {
+ Volumes =
{
- AzureFile = new ContainerInstanceAzureFileVolume(_azSettings.FilesShareName,_azSettings.FilesAccountName)
+ new ContainerVolume("azfiles")
{
- StorageAccountKey = _azSettings.FilesAccountKey
+ AzureFile = new ContainerInstanceAzureFileVolume(_azSettings.FilesShareName,_azSettings.FilesAccountName)
+ {
+ StorageAccountKey = _azSettings.FilesAccountKey
+ },
},
},
- },
- RestartPolicy = ContainerGroupRestartPolicy.Never,
- Sku = ContainerGroupSku.Standard,
- Priority = ContainerGroupPriority.Regular
- };
- await collection.CreateOrUpdateAsync(WaitUntil.Completed, runId, data);
+ RestartPolicy = ContainerGroupRestartPolicy.Never,
+ Sku = ContainerGroupSku.Standard,
+ Priority = ContainerGroupPriority.Regular
+ };
+ await collection.CreateOrUpdateAsync(WaitUntil.Completed, runId, data);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error running sandbox");
+ }
+
}
public async Task Store(SaveOutputRequest request)
{
- var connectionString = $"DefaultEndpointsProtocol=https;AccountName={_azSettings.FilesAccountName};AccountKey={_azSettings.FilesAccountKey};EndpointSuffix=core.windows.net";
- var parentDirName = $"{request.Directory}/{request.Org}-{request.Repo}";
-
- var fileName = $"{request.FileName}.{request.Extension}";
-
- var share = new ShareClient(connectionString, _azSettings.FilesShareName);
- await share.CreateIfNotExistsAsync();
- await share.GetDirectoryClient($"{request.Directory}").CreateIfNotExistsAsync(); ;
-
- var parentDir = share.GetDirectoryClient(parentDirName);
- await parentDir.CreateIfNotExistsAsync();
-
- var parentIssueDir = parentDir.GetSubdirectoryClient($"{request.ParentIssueNumber}");
- await parentIssueDir.CreateIfNotExistsAsync();
-
- var directory = parentIssueDir.GetSubdirectoryClient($"{request.IssueNumber}");
- await directory.CreateIfNotExistsAsync();
-
- var file = directory.GetFileClient(fileName);
- // hack to enable script to save files in the same directory
- var cwdHack = "#!/bin/bash\n cd $(dirname $0)";
- var output = request.Extension == "sh" ? request.Output.Replace("#!/bin/bash", cwdHack) : request.Output;
- using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(output)))
+ try
+ {
+ var connectionString = $"DefaultEndpointsProtocol=https;AccountName={_azSettings.FilesAccountName};AccountKey={_azSettings.FilesAccountKey};EndpointSuffix=core.windows.net";
+ var parentDirName = $"{request.Directory}/{request.Org}-{request.Repo}";
+
+ var fileName = $"{request.FileName}.{request.Extension}";
+
+ var share = new ShareClient(connectionString, _azSettings.FilesShareName);
+ await share.CreateIfNotExistsAsync();
+ await share.GetDirectoryClient($"{request.Directory}").CreateIfNotExistsAsync(); ;
+
+ var parentDir = share.GetDirectoryClient(parentDirName);
+ await parentDir.CreateIfNotExistsAsync();
+
+ var parentIssueDir = parentDir.GetSubdirectoryClient($"{request.ParentIssueNumber}");
+ await parentIssueDir.CreateIfNotExistsAsync();
+
+ var directory = parentIssueDir.GetSubdirectoryClient($"{request.IssueNumber}");
+ await directory.CreateIfNotExistsAsync();
+
+ var file = directory.GetFileClient(fileName);
+ // hack to enable script to save files in the same directory
+ var cwdHack = "#!/bin/bash\n cd $(dirname $0)";
+ var output = request.Extension == "sh" ? request.Output.Replace("#!/bin/bash", cwdHack) : request.Output;
+ using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(output)))
+ {
+ await file.CreateAsync(stream.Length);
+ await file.UploadRangeAsync(
+ new HttpRange(0, stream.Length),
+ stream);
+ }
+ }
+ catch (Exception ex)
{
- await file.CreateAsync(stream.Length);
- await file.UploadRangeAsync(
- new HttpRange(0, stream.Length),
- stream);
+ _logger.LogError(ex, "Error storing output");
}
+
}
}
diff --git a/src/libs/Microsoft.AI.DevTeam/Services/CodeAnalyzer.cs b/src/libs/Microsoft.AI.DevTeam/Services/CodeAnalyzer.cs
index 7153805ed..3e8cb3371 100644
--- a/src/libs/Microsoft.AI.DevTeam/Services/CodeAnalyzer.cs
+++ b/src/libs/Microsoft.AI.DevTeam/Services/CodeAnalyzer.cs
@@ -1,6 +1,7 @@
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
+using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Octokit.Internal;
@@ -14,22 +15,32 @@ public class CodeAnalyzer : IAnalyzeCode
{
private readonly ServiceOptions _serviceOptions;
private readonly HttpClient _httpClient;
+ private readonly ILogger<CodeAnalyzer> _logger;
- public CodeAnalyzer(IOptions<ServiceOptions> serviceOptions, HttpClient httpClient)
+ public CodeAnalyzer(IOptions<ServiceOptions> serviceOptions, HttpClient httpClient, ILogger<CodeAnalyzer> logger)
{
_serviceOptions = serviceOptions.Value;
_httpClient = httpClient;
- _httpClient.BaseAddress = new Uri(_serviceOptions.IngesterUrl);
+ _logger = logger;
+ _httpClient.BaseAddress = new Uri(_serviceOptions.IngesterUrl);
}
public async Task<IEnumerable<CodeAnalysis>> Analyze(string content)
{
- var request = new CodeAnalysisRequest { Content = content };
- var body = new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json");
- var response = await _httpClient.PostAsync("api/AnalyzeCode", body);
- var stringResult = await response.Content.ReadAsStringAsync();
- var result = JsonSerializer.Deserialize<IEnumerable<CodeAnalysis>>(stringResult);
- return result;
+ try
+ {
+ var request = new CodeAnalysisRequest { Content = content };
+ var body = new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json");
+ var response = await _httpClient.PostAsync("api/AnalyzeCode", body);
+ var stringResult = await response.Content.ReadAsStringAsync();
+ var result = JsonSerializer.Deserialize<IEnumerable<CodeAnalysis>>(stringResult);
+ return result;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error analyzing code");
+ return Enumerable.Empty<CodeAnalysis>();
+ }
}
}
diff --git a/src/libs/Microsoft.AI.DevTeam/Services/GithubAuthService.cs b/src/libs/Microsoft.AI.DevTeam/Services/GithubAuthService.cs
index 8752dcb97..7a5156a77 100644
--- a/src/libs/Microsoft.AI.DevTeam/Services/GithubAuthService.cs
+++ b/src/libs/Microsoft.AI.DevTeam/Services/GithubAuthService.cs
@@ -1,3 +1,4 @@
+using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Octokit;
@@ -5,32 +6,42 @@ namespace Microsoft.AI.DevTeam;
public class GithubAuthService
{
private readonly GithubOptions _githubSettings;
+ private readonly ILogger<GithubAuthService> _logger;
- public GithubAuthService(IOptions<GithubOptions> ghOptions)
+ public GithubAuthService(IOptions<GithubOptions> ghOptions, ILogger<GithubAuthService> logger)
{
_githubSettings = ghOptions.Value;
+ _logger = logger;
}
public async Task<GitHubClient> GetGitHubClient()
{
- // Use GitHubJwt library to create the GitHubApp Jwt Token using our private certificate PEM file
- var generator = new GitHubJwt.GitHubJwtFactory(
- new GitHubJwt.StringPrivateKeySource(_githubSettings.AppKey),
- new GitHubJwt.GitHubJwtFactoryOptions
- {
- AppIntegrationId = _githubSettings.AppId, // The GitHub App Id
- ExpirationSeconds = 600 // 10 minutes is the maximum time allowed
- }
- );
-
- var jwtToken = generator.CreateEncodedJwtToken();
- var appClient = new GitHubClient(new ProductHeaderValue("SK-DEV-APP"))
+ try
{
- Credentials = new Credentials(jwtToken, AuthenticationType.Bearer)
- };
- var response = await appClient.GitHubApps.CreateInstallationToken(_githubSettings.InstallationId);
- return new GitHubClient(new ProductHeaderValue($"SK-DEV-APP-Installation{_githubSettings.InstallationId}"))
+ // Use GitHubJwt library to create the GitHubApp Jwt Token using our private certificate PEM file
+ var generator = new GitHubJwt.GitHubJwtFactory(
+ new GitHubJwt.StringPrivateKeySource(_githubSettings.AppKey),
+ new GitHubJwt.GitHubJwtFactoryOptions
+ {
+ AppIntegrationId = _githubSettings.AppId, // The GitHub App Id
+ ExpirationSeconds = 600 // 10 minutes is the maximum time allowed
+ }
+ );
+
+ var jwtToken = generator.CreateEncodedJwtToken();
+ var appClient = new GitHubClient(new ProductHeaderValue("SK-DEV-APP"))
+ {
+ Credentials = new Credentials(jwtToken, AuthenticationType.Bearer)
+ };
+ var response = await appClient.GitHubApps.CreateInstallationToken(_githubSettings.InstallationId);
+ return new GitHubClient(new ProductHeaderValue($"SK-DEV-APP-Installation{_githubSettings.InstallationId}"))
+ {
+ Credentials = new Credentials(response.Token)
+ };
+ }
+ catch (Exception ex)
{
- Credentials = new Credentials(response.Token)
- };
+ _logger.LogError(ex, "Error getting GitHub client");
+ return default;
+ }
}
}
\ No newline at end of file
diff --git a/src/libs/Microsoft.AI.DevTeam/Services/GithubService.cs b/src/libs/Microsoft.AI.DevTeam/Services/GithubService.cs
index f480b1f3b..3fd7d1e6a 100644
--- a/src/libs/Microsoft.AI.DevTeam/Services/GithubService.cs
+++ b/src/libs/Microsoft.AI.DevTeam/Services/GithubService.cs
@@ -25,126 +25,195 @@ public class GithubService : IManageGithub
public async Task CommitToBranch(CommitRequest request)
{
- var connectionString = $"DefaultEndpointsProtocol=https;AccountName={_azSettings.FilesAccountName};AccountKey={_azSettings.FilesAccountKey};EndpointSuffix=core.windows.net";
+ try
+ {
+ var connectionString = $"DefaultEndpointsProtocol=https;AccountName={_azSettings.FilesAccountName};AccountKey={_azSettings.FilesAccountKey};EndpointSuffix=core.windows.net";
- var dirName = $"{request.Dir}/{request.Org}-{request.Repo}/{request.ParentNumber}/{request.Number}";
- var share = new ShareClient(connectionString, _azSettings.FilesShareName);
- var directory = share.GetDirectoryClient(dirName);
+ var dirName = $"{request.Dir}/{request.Org}-{request.Repo}/{request.ParentNumber}/{request.Number}";
+ var share = new ShareClient(connectionString, _azSettings.FilesShareName);
+ var directory = share.GetDirectoryClient(dirName);
- var remaining = new Queue<ShareDirectoryClient>();
- remaining.Enqueue(directory);
- while (remaining.Count > 0)
- {
- var dir = remaining.Dequeue();
- await foreach (var item in dir.GetFilesAndDirectoriesAsync())
+ var remaining = new Queue<ShareDirectoryClient>();
+ remaining.Enqueue(directory);
+ while (remaining.Count > 0)
{
- if (!item.IsDirectory && item.Name != "run.sh") // we don't want the generated script in the PR
+ var dir = remaining.Dequeue();
+ await foreach (var item in dir.GetFilesAndDirectoriesAsync())
{
- try
+ if (!item.IsDirectory && item.Name != "run.sh") // we don't want the generated script in the PR
{
- var file = dir.GetFileClient(item.Name);
- var filePath = file.Path.Replace($"{_azSettings.FilesShareName}/", "")
- .Replace($"{dirName}/", "");
- var fileStream = await file.OpenReadAsync();
- using (var reader = new StreamReader(fileStream, Encoding.UTF8))
+ try
{
- var value = reader.ReadToEnd();
+ var file = dir.GetFileClient(item.Name);
+ var filePath = file.Path.Replace($"{_azSettings.FilesShareName}/", "")
+ .Replace($"{dirName}/", "");
+ var fileStream = await file.OpenReadAsync();
+ using (var reader = new StreamReader(fileStream, Encoding.UTF8))
+ {
+ var value = reader.ReadToEnd();
- await _ghClient.Repository.Content.CreateFile(
- request.Org, request.Repo, filePath,
- new CreateFileRequest($"Commit message", value, request.Branch)); // TODO: add more meaningfull commit message
+ await _ghClient.Repository.Content.CreateFile(
+ request.Org, request.Repo, filePath,
+ new CreateFileRequest($"Commit message", value, request.Branch)); // TODO: add more meaningfull commit message
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, $"Error while uploading file {item.Name}");
}
}
- catch (Exception ex)
+ else if (item.IsDirectory)
{
- _logger.LogError(ex, $"Error while uploading file {item.Name}");
+ remaining.Enqueue(dir.GetSubdirectoryClient(item.Name));
}
}
- else if (item.IsDirectory)
- {
- remaining.Enqueue(dir.GetSubdirectoryClient(item.Name));
- }
}
}
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error committing to branch");
+ }
}
public async Task CreateBranch(CreateBranchRequest request)
{
- var ghRepo = await _ghClient.Repository.Get(request.Org, request.Repo);
- await _ghClient.Git.Reference.CreateBranch(request.Org, request.Repo, request.Branch, ghRepo.DefaultBranch);
+ try
+ {
+ var ghRepo = await _ghClient.Repository.Get(request.Org, request.Repo);
+ await _ghClient.Git.Reference.CreateBranch(request.Org, request.Repo, request.Branch, ghRepo.DefaultBranch);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error creating branch");
+ }
}
public async Task<string> GetMainLanguage(string org, string repo)
{
- var languages = await _ghClient.Repository.GetAllLanguages(org, repo);
- var mainLanguage = languages.OrderByDescending(l => l.NumberOfBytes).First();
- return mainLanguage.Name;
+ try
+ {
+ var languages = await _ghClient.Repository.GetAllLanguages(org, repo);
+ var mainLanguage = languages.OrderByDescending(l => l.NumberOfBytes).First();
+ return mainLanguage.Name;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error getting main language");
+ return default;
+ }
}
public async Task<NewIssueResponse> CreateIssue(CreateIssueRequest request)
{
- var newIssue = new NewIssue($"{request.Label} chain for #{request.ParentNumber}")
+ try
{
- Body = request.Input,
+ var newIssue = new NewIssue($"{request.Label} chain for #{request.ParentNumber}")
+ {
+ Body = request.Input,
- };
- newIssue.Labels.Add(request.Label);
- var issue = await _ghClient.Issue.Create(request.Org, request.Repo, newIssue);
- var commentBody = $" - [ ] #{issue.Number} - tracks {request.Label}";
- var comment = await _ghClient.Issue.Comment.Create(request.Org, request.Repo, (int)request.ParentNumber, commentBody);
- return new NewIssueResponse
+ };
+ newIssue.Labels.Add(request.Label);
+ var issue = await _ghClient.Issue.Create(request.Org, request.Repo, newIssue);
+ var commentBody = $" - [ ] #{issue.Number} - tracks {request.Label}";
+ var comment = await _ghClient.Issue.Comment.Create(request.Org, request.Repo, (int)request.ParentNumber, commentBody);
+ return new NewIssueResponse
+ {
+ IssueNumber = issue.Number,
+ CommentId = comment.Id
+ };
+ }
+ catch (Exception ex)
{
- IssueNumber = issue.Number,
- CommentId = comment.Id
- };
-
+ _logger.LogError(ex, "Error creating issue");
+ return default;
+ }
}
public async Task CreatePR(CreatePRRequest request)
{
- var ghRepo = await _ghClient.Repository.Get(request.Org, request.Repo);
- await _ghClient.PullRequest.Create(request.Org, request.Repo, new NewPullRequest($"New app #{request.Number}", request.Branch, ghRepo.DefaultBranch));
+ try
+ {
+ var ghRepo = await _ghClient.Repository.Get(request.Org, request.Repo);
+ await _ghClient.PullRequest.Create(request.Org, request.Repo, new NewPullRequest($"New app #{request.Number}", request.Branch, ghRepo.DefaultBranch));
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error creating PR");
+ }
+
}
public async Task MarkTaskComplete(MarkTaskCompleteRequest request)
{
- var comment = await _ghClient.Issue.Comment.Get(request.Org, request.Repo, request.CommentId);
- var updatedComment = comment.Body.Replace("[ ]", "[x]");
- await _ghClient.Issue.Comment.Update(request.Org, request.Repo, request.CommentId, updatedComment);
+ try
+ {
+ var comment = await _ghClient.Issue.Comment.Get(request.Org, request.Repo, request.CommentId);
+ var updatedComment = comment.Body.Replace("[ ]", "[x]");
+ await _ghClient.Issue.Comment.Update(request.Org, request.Repo, request.CommentId, updatedComment);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error marking task complete");
+ }
+
}
public async Task PostComment(PostCommentRequest request)
{
- await _ghClient.Issue.Comment.Create(request.Org, request.Repo, request.Number, request.Content);
+ try
+ {
+ await _ghClient.Issue.Comment.Create(request.Org, request.Repo, request.Number, request.Content);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error posting comment");
+ }
+
}
- public async Task<IEnumerable<FileResponse>> GetFiles(string org, string repo, string branch, Func<RepositoryContent,bool> filter)
+ public async Task<IEnumerable<FileResponse>> GetFiles(string org, string repo, string branch, Func<RepositoryContent, bool> filter)
{
- var items = await _ghClient.Repository.Content.GetAllContentsByRef(org, repo, branch);
- return await CollectFiles(org, repo, branch, items, filter);
+ try
+ {
+ var items = await _ghClient.Repository.Content.GetAllContentsByRef(org, repo, branch);
+ return await CollectFiles(org, repo, branch, items, filter);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error getting files");
+ return Enumerable.Empty<FileResponse>();
+ }
}
- private async Task<IEnumerable<FileResponse>> CollectFiles(string org, string repo, string branch, IReadOnlyList<RepositoryContent> items, Func<RepositoryContent,bool> filter)
+ private async Task<IEnumerable<FileResponse>> CollectFiles(string org, string repo, string branch, IReadOnlyList<RepositoryContent> items, Func<RepositoryContent, bool> filter)
{
- var result = new List<FileResponse>();
- foreach(var item in items)
+ try
{
- if (item.Type == ContentType.File && filter(item))
+ var result = new List<FileResponse>();
+ foreach (var item in items)
{
- var content = await _httpClient.GetStringAsync(item.DownloadUrl);
- result.Add(new FileResponse
+ if (item.Type == ContentType.File && filter(item))
{
- Name = item.Name,
- Content = content
- });
- }
- else if (item.Type == ContentType.Dir)
- {
- var subItems = await _ghClient.Repository.Content.GetAllContentsByRef(org, repo,item.Path, branch);
- result.AddRange(await CollectFiles(org, repo, branch, subItems, filter));
+ var content = await _httpClient.GetStringAsync(item.DownloadUrl);
+ result.Add(new FileResponse
+ {
+ Name = item.Name,
+ Content = content
+ });
+ }
+ else if (item.Type == ContentType.Dir)
+ {
+ var subItems = await _ghClient.Repository.Content.GetAllContentsByRef(org, repo, item.Path, branch);
+ result.AddRange(await CollectFiles(org, repo, branch, subItems, filter));
+ }
}
+ return result;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error collecting files");
+ return Enumerable.Empty<FileResponse>();
}
- return result;
}
}
@@ -164,7 +233,7 @@ public interface IManageGithub
Task CommitToBranch(CommitRequest request);
Task PostComment(PostCommentRequest request);
- Task<IEnumerable<FileResponse>> GetFiles(string org, string repo, string branch, Func<RepositoryContent,bool> filter);
+ Task<IEnumerable<FileResponse>> GetFiles(string org, string repo, string branch, Func<RepositoryContent, bool> filter);
Task<string> GetMainLanguage(string org, string repo);
}