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 6 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>
/// Propagate exception from within semantic function
/// </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();
}

101 changes: 27 additions & 74 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 @@ -296,7 +286,7 @@ public async Task<SKContext> ChatAsync(
await this.UpdateChatMessageContentAsync(planJson, messageId);
}

ChatMessage? chatMessage;
ChatMessage chatMessage;
if (chatContext.Variables.ContainsKey("userCancelledPlan"))
{
// Save hardcoded response if user cancelled plan
Expand All @@ -308,11 +298,6 @@ public async Task<SKContext> ChatAsync(
chatMessage = await this.GetChatResponseAsync(chatId, userId, chatContext, cancellationToken);
}

if (chatMessage == null)
{
context.Fail(chatContext.LastErrorDescription);
return context;
}
context.Variables.Update(chatMessage.Content);

if (chatMessage.TokenUsage != null)
Expand All @@ -321,7 +306,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 All @@ -336,23 +321,17 @@ public async Task<SKContext> ChatAsync(
/// <param name="userId">The user ID</param>
/// <param name="chatContext">The SKContext.</param>
/// <returns>The created chat message containing the model-generated response.</returns>
private async Task<ChatMessage?> GetChatResponseAsync(string chatId, string userId, SKContext chatContext, CancellationToken cancellationToken)
private async Task<ChatMessage> GetChatResponseAsync(string chatId, string userId, SKContext chatContext, CancellationToken cancellationToken)
{
// Get the audience
await this.UpdateBotResponseStatusOnClient(chatId, "Extracting audience");
var audience = await this.GetAudienceAsync(chatContext);
if (chatContext.ErrorOccurred)
{
return null;
}
chatContext.ThrowIfFailed();

// Extract user intent from the conversation history.
await this.UpdateBotResponseStatusOnClient(chatId, "Extracting user intent");
var userIntent = await this.GetUserIntentAsync(chatContext);
if (chatContext.ErrorOccurred)
{
return null;
}
chatContext.ThrowIfFailed();

chatContext.Variables.Set("audience", audience);
chatContext.Variables.Set("userIntent", userIntent);
Expand All @@ -365,10 +344,7 @@ public async Task<SKContext> ChatAsync(
await this.UpdateBotResponseStatusOnClient(chatId, "Acquiring external information from planner");
var externalInformationTokenLimit = (int)(remainingToken * this._promptOptions.ExternalInformationContextWeight);
var planResult = await this.AcquireExternalInformationAsync(chatContext, userIntent, externalInformationTokenLimit);
if (chatContext.ErrorOccurred)
{
return null;
}
chatContext.ThrowIfFailed();

// If plan is suggested, send back to user for approval before running
var proposedPlan = this._externalInformationSkill.ProposedPlan;
Expand All @@ -389,19 +365,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 All @@ -414,10 +383,7 @@ public async Task<SKContext> ChatAsync(
{
await this.UpdateBotResponseStatusOnClient(chatId, "Extracting chat history");
chatHistory = await this.ExtractChatHistoryAsync(chatId, chatHistoryTokenLimit);
if (chatContext.ErrorOccurred)
{
return null;
}
chatContext.ThrowIfFailed();
chatContextText = $"{chatContextText}\n{chatHistory}";
}

Expand All @@ -436,12 +402,9 @@ 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)
{
return null;
}
chatContext.ThrowIfFailed();

// Stream the response to the client
await this.UpdateBotResponseStatusOnClient(chatId, "Generating bot response");
Expand Down Expand Up @@ -480,17 +443,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 +469,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 +490,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 +502,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 +520,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 +546,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
Loading