Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update SK packages #120

Merged
merged 7 commits into from
Aug 8, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions webapi/CopilotChat/Controllers/BotController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ public async Task<ActionResult<ChatSession>> UploadAsync(

return this.CreatedAtAction(
nameof(ChatHistoryController.GetChatSessionByIdAsync),
nameof(ChatHistoryController).Replace("Controller", "", StringComparison.OrdinalIgnoreCase),
nameof(ChatHistoryController).Replace("Controller", string.Empty, StringComparison.OrdinalIgnoreCase),
new { chatId },
newChat);
}
Expand Down Expand Up @@ -208,7 +208,7 @@ private async Task GetMemoryRecordsAndAppendToEmbeddingsAsync(
IKernel kernel,
string collectionName,
List<KeyValuePair<string, List<MemoryQueryResult>>> embeddings,
string newCollectionName = "")
string? newCollectionName = null)
{
List<MemoryQueryResult> collectionMemoryRecords;
try
Expand Down
10 changes: 5 additions & 5 deletions webapi/CopilotChat/Controllers/ChatController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public async Task<IActionResult> ChatAsync(
return this.BadRequest(string.Concat(aiException.Message, " - Detail: " + aiException.Detail));
}

return this.BadRequest(result.LastErrorDescription);
return this.BadRequest(result.LastException!.Message);
glahaye marked this conversation as resolved.
Show resolved Hide resolved
}

AskResult chatSkillAskResult = new()
Expand Down Expand Up @@ -174,15 +174,15 @@ private async Task RegisterPlannerSkillsAsync(CopilotChatPlanner planner, Dictio
this._logger.LogInformation("Registering Klarna plugin");

// Register the Klarna shopping ChatGPT plugin with the planner's kernel. There is no authentication required for this plugin.
await planner.Kernel.ImportChatGptPluginSkillFromUrlAsync("KlarnaShoppingPlugin", new Uri("https://www.klarna.com/.well-known/ai-plugin.json"), new OpenApiSkillExecutionParameters());
await planner.Kernel.ImportAIPluginAsync("KlarnaShoppingPlugin", new Uri("https://www.klarna.com/.well-known/ai-plugin.json"), new OpenApiSkillExecutionParameters());
}

// GitHub
if (openApiSkillsAuthHeaders.TryGetValue("GITHUB", out string? GithubAuthHeader))
{
this._logger.LogInformation("Enabling GitHub plugin.");
BearerAuthenticationProvider authenticationProvider = new(() => Task.FromResult(GithubAuthHeader));
await planner.Kernel.ImportOpenApiSkillFromFileAsync(
await planner.Kernel.ImportAIPluginAsync(
teresaqhoang marked this conversation as resolved.
Show resolved Hide resolved
skillName: "GitHubPlugin",
filePath: Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "CopilotChat", "Skills", "OpenApiPlugins/GitHubPlugin/openapi.json"),
new OpenApiSkillExecutionParameters
Expand All @@ -198,7 +198,7 @@ await planner.Kernel.ImportOpenApiSkillFromFileAsync(
var authenticationProvider = new BasicAuthenticationProvider(() => { return Task.FromResult(JiraAuthHeader); });
var hasServerUrlOverride = variables.TryGetValue("jira-server-url", out string? serverUrlOverride);

await planner.Kernel.ImportOpenApiSkillFromFileAsync(
await planner.Kernel.ImportAIPluginAsync(
skillName: "JiraPlugin",
filePath: Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "CopilotChat", "Skills", "OpenApiPlugins/JiraPlugin/openapi.json"),
new OpenApiSkillExecutionParameters
Expand Down Expand Up @@ -241,7 +241,7 @@ await planner.Kernel.ImportOpenApiSkillFromFileAsync(
var requiresAuth = !plugin.AuthType.Equals("none", StringComparison.OrdinalIgnoreCase);
BearerAuthenticationProvider authenticationProvider = new(() => Task.FromResult(PluginAuthValue));

await planner.Kernel.ImportChatGptPluginSkillFromUrlAsync(
await planner.Kernel.ImportAIPluginAsync(
$"{plugin.NameForModel}Plugin",
uriBuilder.Uri,
new OpenApiSkillExecutionParameters
Expand Down
4 changes: 2 additions & 2 deletions webapi/CopilotChat/Controllers/ChatMemoryController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ private bool ValidateMemoryName(string memoryName)
}

/// <summary>
/// Sanitizes the log input by removing new line characters.
/// Sanitizes the log input by removing new line characters.
/// This helps prevent log forgery attacks from malicious text.
/// </summary>
/// <remarks>
Expand All @@ -124,7 +124,7 @@ private bool ValidateMemoryName(string memoryName)
/// <returns>The sanitized input.</returns>
private string SanitizeLogInput(string input)
{
return input.Replace(Environment.NewLine, "", StringComparison.Ordinal);
return input.Replace(Environment.NewLine, string.Empty, StringComparison.Ordinal);
}

# endregion
Expand Down
2 changes: 1 addition & 1 deletion webapi/CopilotChat/Controllers/SpeechTokenController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,6 @@ private async Task<TokenResult> FetchTokenAsync(string fetchUri, string subscrip
return new TokenResult { Token = token, ResponseCode = response.StatusCode };
}

return new TokenResult { Token = "", ResponseCode = HttpStatusCode.NotFound };
return new TokenResult { ResponseCode = HttpStatusCode.NotFound };
}
}
13 changes: 13 additions & 0 deletions webapi/CopilotChat/Extensions/SemanticKernelExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.Extensions.Options;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Orchestration;
using SemanticKernel.Service.CopilotChat.Hubs;
using SemanticKernel.Service.CopilotChat.Options;
using SemanticKernel.Service.CopilotChat.Skills.ChatSkills;
Expand Down Expand Up @@ -63,6 +64,18 @@ public static IKernel RegisterCopilotChatSkills(this IKernel kernel, IServicePro
return kernel;
}

/// <summary>
/// Propegate exception from within semantic function
crickman marked this conversation as resolved.
Show resolved Hide resolved
/// </summary>
public static void ThrowIfFailed(this SKContext context)
{
if (context.ErrorOccurred)
{
context.Logger.LogError(context.LastException, "{0}", context.LastException?.Message);
throw context.LastException!;
glahaye marked this conversation as resolved.
Show resolved Hide resolved
}
}

/// <summary>
/// Add the completion backend to the kernel config for the planner.
/// </summary>
Expand Down
4 changes: 2 additions & 2 deletions webapi/CopilotChat/Models/ChatMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public ChatMessage(
string userName,
string chatId,
string content,
string prompt = "",
string? prompt = null,
AuthorRoles authorRole = AuthorRoles.User,
ChatMessageType type = ChatMessageType.Message,
Dictionary<string, int>? tokenUsage = null)
Expand All @@ -144,7 +144,7 @@ public ChatMessage(
this.ChatId = chatId;
this.Content = content;
this.Id = Guid.NewGuid().ToString();
this.Prompt = prompt;
this.Prompt = prompt ?? string.Empty;
this.AuthorRole = authorRole;
this.Type = type;
this.TokenUsage = tokenUsage;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,3 @@ public class MemoriesStoreOptionResponse
[JsonPropertyName("memoriesStore")]
public MemoriesStoreOptionResponse MemoriesStore { get; set; } = new MemoriesStoreOptionResponse();
}

73 changes: 23 additions & 50 deletions webapi/CopilotChat/Skills/ChatSkills/ChatSkill.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.AI.ChatCompletion;
using Microsoft.SemanticKernel.AI.TextCompletion;
using Microsoft.SemanticKernel.Diagnostics;
using Microsoft.SemanticKernel.Orchestration;
using Microsoft.SemanticKernel.SkillDefinition;
using Microsoft.SemanticKernel.TemplateEngine;
using SemanticKernel.Service.CopilotChat.Extensions;
using SemanticKernel.Service.CopilotChat.Hubs;
using SemanticKernel.Service.CopilotChat.Models;
using SemanticKernel.Service.CopilotChat.Options;
Expand Down Expand Up @@ -150,12 +150,7 @@ public async Task<string> ExtractUserIntentAsync(SKContext context)
// Get token usage from ChatCompletion result and add to context
TokenUtilities.GetFunctionTokenUsage(result, context, "SystemIntentExtraction");

if (result.ErrorOccurred)
{
context.Log.LogError("{0}: {1}", result.LastErrorDescription, result.LastException);
context.Fail(result.LastErrorDescription);
return string.Empty;
}
result.ThrowIfFailed();
alliscode marked this conversation as resolved.
Show resolved Hide resolved
glahaye marked this conversation as resolved.
Show resolved Hide resolved

return $"User intent: {result}";
}
Expand Down Expand Up @@ -196,12 +191,7 @@ public async Task<string> ExtractAudienceAsync(SKContext context)
// Get token usage from ChatCompletion result and add to context
TokenUtilities.GetFunctionTokenUsage(result, context, "SystemAudienceExtraction");

if (result.ErrorOccurred)
{
context.Log.LogError("{0}: {1}", result.LastErrorDescription, result.LastException);
context.Fail(result.LastErrorDescription);
return string.Empty;
}
result.ThrowIfFailed();

return $"List of participants: {result}";
}
Expand All @@ -220,7 +210,7 @@ public async Task<string> ExtractChatHistoryAsync(

var remainingToken = tokenLimit;

string historyText = "";
string historyText = string.Empty;
foreach (var chatMessage in sortedMessages)
{
var formattedMessage = chatMessage.ToFormattedString();
Expand Down Expand Up @@ -308,10 +298,10 @@ public async Task<SKContext> ChatAsync(
chatMessage = await this.GetChatResponseAsync(chatId, userId, chatContext, cancellationToken);
}

if (chatMessage == null)
if (chatMessage == null) // $$$
crickman marked this conversation as resolved.
Show resolved Hide resolved
crickman marked this conversation as resolved.
Show resolved Hide resolved
{
context.Fail(chatContext.LastErrorDescription);
return context;
context.Logger.LogError(context.LastException, "{0}", context.LastException?.Message);
throw context.LastException!;
glahaye marked this conversation as resolved.
Show resolved Hide resolved
}
context.Variables.Update(chatMessage.Content);

Expand All @@ -321,7 +311,7 @@ public async Task<SKContext> ChatAsync(
}
else
{
context.Log.LogWarning("ChatSkill token usage unknown. Ensure token management has been implemented correctly.");
context.Logger.LogWarning("ChatSkill token usage unknown. Ensure token management has been implemented correctly.");
}

return context;
Expand Down Expand Up @@ -389,19 +379,12 @@ public async Task<SKContext> ChatAsync(
await this.UpdateBotResponseStatusOnClient(chatId, "Extracting semantic and document memories");
var chatMemoriesTokenLimit = (int)(remainingToken * this._promptOptions.MemoriesResponseContextWeight);
var documentContextTokenLimit = (int)(remainingToken * this._promptOptions.DocumentContextWeight);
string[] tasks;
try
{
tasks = await Task.WhenAll<string>(
this._semanticChatMemorySkill.QueryMemoriesAsync(userIntent, chatId, chatMemoriesTokenLimit, this._kernel.Memory),
this._documentMemorySkill.QueryDocumentsAsync(userIntent, chatId, documentContextTokenLimit, this._kernel.Memory)
);
}
catch (SKException ex)
{
chatContext.Fail(ex.Message, ex);
return null;
}

string[] tasks = await Task.WhenAll<string>(
this._semanticChatMemorySkill.QueryMemoriesAsync(userIntent, chatId, chatMemoriesTokenLimit, this._kernel.Memory),
glahaye marked this conversation as resolved.
Show resolved Hide resolved
this._documentMemorySkill.QueryDocumentsAsync(userIntent, chatId, documentContextTokenLimit, this._kernel.Memory)
);

var chatMemories = tasks[0];
var documentMemories = tasks[1];

Expand Down Expand Up @@ -436,7 +419,7 @@ public async Task<SKContext> ChatAsync(
var promptView = new BotResponsePrompt(renderedPrompt, this._promptOptions.SystemDescription, this._promptOptions.SystemResponse, audience, userIntent, chatMemories, documentMemories, planResult, chatHistory, systemChatContinuation);

// Calculate token usage of prompt template
chatContext.Variables.Set(TokenUtilities.GetFunctionKey(chatContext.Log, "SystemMetaPrompt")!, TokenUtilities.TokenCount(renderedPrompt).ToString(CultureInfo.InvariantCulture));
chatContext.Variables.Set(TokenUtilities.GetFunctionKey(chatContext.Logger, "SystemMetaPrompt")!, TokenUtilities.TokenCount(renderedPrompt).ToString(CultureInfo.InvariantCulture));

if (chatContext.ErrorOccurred)
{
Expand Down Expand Up @@ -480,17 +463,14 @@ private async Task<string> GetAudienceAsync(SKContext context)
var audience = await this.ExtractAudienceAsync(audienceContext);

// Copy token usage into original chat context
var functionKey = TokenUtilities.GetFunctionKey(context.Log, "SystemAudienceExtraction")!;
var functionKey = TokenUtilities.GetFunctionKey(context.Logger, "SystemAudienceExtraction")!;
if (audienceContext.Variables.TryGetValue(functionKey, out string? tokenUsage))
{
context.Variables.Set(functionKey, tokenUsage);
}

// Propagate the error
if (audienceContext.ErrorOccurred)
{
context.Fail(audienceContext.LastErrorDescription);
}
audienceContext.ThrowIfFailed();

return audience;
}
Expand All @@ -509,17 +489,13 @@ private async Task<string> GetUserIntentAsync(SKContext context)
userIntent = await this.ExtractUserIntentAsync(intentContext);

// Copy token usage into original chat context
var functionKey = TokenUtilities.GetFunctionKey(context.Log, "SystemIntentExtraction")!;
var functionKey = TokenUtilities.GetFunctionKey(context.Logger, "SystemIntentExtraction")!;
if (intentContext.Variables.TryGetValue(functionKey!, out string? tokenUsage))
{
context.Variables.Set(functionKey!, tokenUsage);
}

// Propagate the error
if (intentContext.ErrorOccurred)
{
context.Fail(intentContext.LastErrorDescription);
}
intentContext.ThrowIfFailed();
}

return userIntent;
Expand All @@ -534,7 +510,7 @@ private async Task<string> GetUserIntentAsync(SKContext context)
/// <param name="tokenLimit">Maximum number of tokens.</param>
private Task<string> QueryChatMemoriesAsync(SKContext context, string userIntent, int tokenLimit)
{
return this._semanticChatMemorySkill.QueryMemoriesAsync(userIntent, context["chatId"], tokenLimit, this._kernel.Memory);
return this._semanticChatMemorySkill.QueryMemoriesAsync(userIntent, context.Variables["chatId"], tokenLimit, this._kernel.Memory);
glahaye marked this conversation as resolved.
Show resolved Hide resolved
}

/// <summary>
Expand All @@ -546,7 +522,7 @@ private Task<string> QueryChatMemoriesAsync(SKContext context, string userIntent
/// <param name="tokenLimit">Maximum number of tokens.</param>
private Task<string> QueryDocumentsAsync(SKContext context, string userIntent, int tokenLimit)
{
return this._documentMemorySkill.QueryDocumentsAsync(userIntent, context["chatId"], tokenLimit, this._kernel.Memory);
return this._documentMemorySkill.QueryDocumentsAsync(userIntent, context.Variables["chatId"], tokenLimit, this._kernel.Memory);
}

/// <summary>
Expand All @@ -564,10 +540,7 @@ private async Task<string> AcquireExternalInformationAsync(SKContext context, st
var plan = await this._externalInformationSkill.AcquireExternalInformationAsync(userIntent, planContext);

// Propagate the error
if (planContext.ErrorOccurred)
{
context.Fail(planContext.LastErrorDescription);
}
planContext.ThrowIfFailed();

return plan;
}
Expand All @@ -593,7 +566,7 @@ private async Task<ChatMessage> SaveNewMessageAsync(string message, string userI
userName,
chatId,
message,
"",
string.Empty,
ChatMessage.AuthorRoles.User,
// Default to a standard message if the `type` is not recognized
Enum.TryParse(type, out ChatMessage.ChatMessageType typeAsEnum) && Enum.IsDefined(typeof(ChatMessage.ChatMessageType), typeAsEnum)
Expand Down
14 changes: 7 additions & 7 deletions webapi/CopilotChat/Skills/ChatSkills/ExternalInformationSkill.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,15 +95,15 @@ public async Task<string> AcquireExternalInformationAsync(
string planJson = JsonSerializer.Serialize(deserializedPlan.Plan);
// Reload the plan with the planner's kernel so
// it has full context to be executed
var newPlanContext = new SKContext(null, this._planner.Kernel.Skills, this._planner.Kernel.Log);
var newPlanContext = new SKContext(null, this._planner.Kernel.Skills, this._planner.Kernel.Logger);
var plan = Plan.FromJson(planJson, newPlanContext);

// Invoke plan
newPlanContext = await plan.InvokeAsync(newPlanContext);
var functionsUsed = $"FUNCTIONS EXECUTED: {string.Join("; ", this.GetPlanSteps(plan))}.";

int tokenLimit =
int.Parse(context["tokenLimit"], new NumberFormatInfo()) -
int.Parse(context.Variables["tokenLimit"], new NumberFormatInfo()) -
TokenUtilities.TokenCount(PromptPreamble) -
TokenUtilities.TokenCount(PromptPostamble) -
TokenUtilities.TokenCount(functionsUsed) -
Expand Down Expand Up @@ -139,7 +139,7 @@ public async Task<string> AcquireExternalInformationAsync(
{ // TODO: [Issue #2256] Remove InvalidPlan retry logic once Core team stabilizes planner
try
{
plan = await this._planner.CreatePlanAsync($"Given the following context, accomplish the user intent.\nContext:\n{contextString}\nUser Intent:{userIntent}", context.Log);
plan = await this._planner.CreatePlanAsync($"Given the following context, accomplish the user intent.\nContext:\n{contextString}\nUser Intent:{userIntent}", context.Logger);
}
catch (Exception e) when (this.IsRetriableError(e))
{
Expand All @@ -149,7 +149,7 @@ public async Task<string> AcquireExternalInformationAsync(
retriesAvail = e is PlanningException ? 0 : retriesAvail--;

// Retry plan creation if LLM returned response that doesn't contain valid plan (invalid XML or JSON).
context.Log.LogWarning("Retrying CreatePlan on error: {0}", e.Message);
context.Logger.LogWarning("Retrying CreatePlan on error: {0}", e.Message);
continue;
}
throw;
Expand Down Expand Up @@ -241,11 +241,11 @@ private bool TryExtractJsonFromOpenApiPlanResult(SKContext context, string openA
}
catch (JsonException)
{
context.Log.LogDebug("Unable to extract JSON from planner response, it is likely not from an OpenAPI skill.");
context.Logger.LogDebug("Unable to extract JSON from planner response, it is likely not from an OpenAPI skill.");
}
catch (InvalidOperationException)
{
context.Log.LogDebug("Unable to extract JSON from planner response, it may already be proper JSON.");
context.Logger.LogDebug("Unable to extract JSON from planner response, it may already be proper JSON.");
}

json = string.Empty;
Expand Down Expand Up @@ -289,7 +289,7 @@ private string OptimizeOpenApiSkillJson(string jsonContent, int tokenLimit, Plan

// Some APIs will return a JSON response with one property key representing an embedded answer.
// Extract this value for further processing
string resultsDescriptor = "";
string resultsDescriptor = string.Empty;

if (document.RootElement.ValueKind == JsonValueKind.Object)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ internal static async Task ExtractSemanticChatMemoryAsync(
{
// Skip semantic memory extraction for this item if it fails.
// We cannot rely on the model to response with perfect Json each time.
context.Log.LogInformation("Unable to extract semantic memory for {0}: {1}. Continuing...", memoryName, ex.Message);
context.Logger.LogInformation("Unable to extract semantic memory for {0}: {1}. Continuing...", memoryName, ex.Message);
continue;
}
}
Expand Down
Loading