Skip to content

Commit 326d317

Browse files
authored
Shortening plan object in chat history (#1306)
### Motivation and Context Truncating plan object to intent only in chat history to save on token limits. ![image](https://github.com/microsoft/semantic-kernel/assets/125500434/e8690c10-ac9e-4ae4-8506-6fd1426f1818)
1 parent bfe6369 commit 326d317

File tree

1 file changed

+21
-2
lines changed
  • samples/apps/copilot-chat-app/webapi/CopilotChat/Skills/ChatSkills

1 file changed

+21
-2
lines changed

samples/apps/copilot-chat-app/webapi/CopilotChat/Skills/ChatSkills/ChatSkill.cs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Globalization;
66
using System.Linq;
77
using System.Text.Json;
8+
using System.Text.RegularExpressions;
89
using System.Threading.Tasks;
910
using Microsoft.Extensions.Logging;
1011
using Microsoft.Extensions.Options;
@@ -156,10 +157,28 @@ public async Task<string> ExtractChatHistoryAsync(SKContext context)
156157
foreach (var chatMessage in sortedMessages)
157158
{
158159
var formattedMessage = chatMessage.ToFormattedString();
160+
161+
// Plan object is not meaningful content in generating bot response, so shorten to intent only to save on tokens
162+
if (formattedMessage.Contains("proposedPlan\":", StringComparison.InvariantCultureIgnoreCase))
163+
{
164+
string pattern = @"(\[.*?\]).*User Intent:User intent: (.*)(?=""}})";
165+
Match match = Regex.Match(formattedMessage, pattern);
166+
if (match.Success)
167+
{
168+
string timestamp = match.Groups[1].Value.Trim();
169+
string userIntent = match.Groups[2].Value.Trim();
170+
171+
formattedMessage = $"{timestamp} Bot proposed plan to fulfill user intent: {userIntent}";
172+
}
173+
else
174+
{
175+
formattedMessage = "Bot proposed plan";
176+
}
177+
}
178+
159179
var tokenCount = Utilities.TokenCount(formattedMessage);
160180

161-
// Plan object is not meaningful content in generating chat response, exclude it
162-
if (remainingToken - tokenCount > 0 && !formattedMessage.Contains("proposedPlan\\\":", StringComparison.InvariantCultureIgnoreCase))
181+
if (remainingToken - tokenCount >= 0)
163182
{
164183
historyText = $"{formattedMessage}\n{historyText}";
165184
remainingToken -= tokenCount;

0 commit comments

Comments
 (0)