-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCommentHandler.cs
253 lines (223 loc) · 10.4 KB
/
CommentHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
using System;
using System.ClientModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Word;
using OpenAI.Chat;
using Task = System.Threading.Tasks.Task;
using Word = Microsoft.Office.Interop.Word;
namespace TextForge
{
internal class CommentHandler
{
private static int _prevNumComments = 0;
private static bool _isDraftingComment = false;
public static async void Document_CommentsEventHandler(Word.Selection selection)
{
try
{
// For preventing unnecessary iteration of this function every time something changes in Word.
int numComments = Globals.ThisAddIn.Application.ActiveDocument.Comments.Count;
if (numComments == _prevNumComments) return;
if (await AICommentReplyTask())
numComments++;
if (await UserMentionTask())
numComments++;
_prevNumComments = numComments;
}
catch (Exception ex)
{
CommonUtils.DisplayError(ex);
}
}
private static async Task<bool> AICommentReplyTask()
{
var comments = GetUnansweredAIComments(Globals.ThisAddIn.Application.ActiveDocument.Comments);
var doc = Globals.ThisAddIn.Application.ActiveDocument;
foreach (var comment in comments)
{
List<ChatMessage> chatHistory = new List<ChatMessage>() {
new UserChatMessage($@"{Forge.CultureHelper.GetLocalizedString("[Review] chatHistory #1")}\n""{CommonUtils.SubstringTokens(comment.Range.Text, (int)(ThisAddIn.ContextLength * 0.2))}"""),
new UserChatMessage(Forge.CultureHelper.GetLocalizedString("(CommentHandler.cs) [AICommentReplyTask] UserChatMessage #2"))
};
chatHistory.AddRange(GetCommentMessages(comment));
chatHistory.Add(new UserChatMessage(@$"{Forge.CultureHelper.GetLocalizedString("(CommentHandler.cs) [AICommentReplyTask] UserChatMessage #3")}:\n""{comment.Scope.Text}"""));
try
{
if (_isDraftingComment) return false; // TODO: is this really necessary?
_isDraftingComment = true;
await AddComment(
comment.Replies,
comment.Range,
RAGControl.AskQuestion(
Forge.CommentSystemPrompt,
chatHistory,
Globals.ThisAddIn.Application.ActiveDocument.Range(),
0.5f,
doc
)
);
_isDraftingComment = false;
return true;
}
catch (OperationCanceledException ex)
{
CommonUtils.DisplayWarning(ex);
}
}
return false;
}
private static async Task<bool> UserMentionTask()
{
var comments = GetUnansweredMentionedComments(Globals.ThisAddIn.Application.ActiveDocument.Comments);
var doc = Globals.ThisAddIn.Application.ActiveDocument;
foreach (var comment in comments)
{
List<ChatMessage> chatHistory = new List<ChatMessage>();
chatHistory.AddRange(GetCommentMessagesWithoutMention(comment));
chatHistory.Add(new UserChatMessage(@$"{Forge.CultureHelper.GetLocalizedString("(CommentHandler.cs) [AICommentReplyTask] UserChatMessage #3")}:\n""{comment.Scope.Text}"""));
try
{
if (_isDraftingComment) return false; // TODO: is this really necessary?
_isDraftingComment = true;
await AddComment(
comment.Replies,
comment.Range,
RAGControl.AskQuestion(
new SystemChatMessage(ThisAddIn.SystemPromptLocalization["(CommentHandler.cs) [AIUserMentionTask] UserMentionSystemPrompt"]),
chatHistory,
Globals.ThisAddIn.Application.ActiveDocument.Range(),
0.5f,
doc
)
);
_isDraftingComment = false;
return true;
}
catch (OperationCanceledException ex)
{
CommonUtils.DisplayWarning(ex);
}
}
return false;
}
private static IEnumerable<ChatMessage> GetCommentMessagesWithoutMention(Comment parentComment)
{
string modelName = $"@{ThisAddIn.Model}";
List<ChatMessage> chatHistory = new List<ChatMessage>()
{
new UserChatMessage(GetCleanedCommentText(parentComment, modelName))
};
Comments childrenComments = parentComment.Replies; // Includes parent comment
for (int i = 1; i <= childrenComments.Count; i++)
{
var comment = childrenComments[i];
string cleanText = GetCleanedCommentText(parentComment, modelName);
chatHistory.Add(
(i % 2 == 1) ? new AssistantChatMessage(cleanText) : new UserChatMessage(cleanText)
);
}
return chatHistory;
}
private static string GetCleanedCommentText(Comment c, string modelName)
{
string commentText = c.Range.Text;
return commentText.Contains(modelName) ? commentText.Remove(commentText.IndexOf(modelName), modelName.Length).TrimStart() : commentText;
}
// Converts Word Comment object into a list of ChatMessage that can be fed into the OpenAI API
private static IEnumerable<ChatMessage> GetCommentMessages(Comment parentComment)
{
List<ChatMessage> chatHistory = new List<ChatMessage>()
{
new UserChatMessage(parentComment.Range.Text)
};
Comments childrenComments = parentComment.Replies;
for (int i = 1; i <= childrenComments.Count; i++)
{
var comment = childrenComments[i];
chatHistory.Add(
(i % 2 == 1) ? new AssistantChatMessage(comment.Range.Text) : new UserChatMessage(comment.Range.Text)
);
}
return chatHistory;
}
// Checks if the user mentions the AI with '@' character. Example: "@qwen2.5:1.5b"
private static IEnumerable<Comment> GetUnansweredMentionedComments(Comments allComments)
{
List<Comment> comments = new List<Comment>();
foreach (Comment c in allComments)
if (
c.Ancestor == null &&
( c.Range.Text.Contains($"@{ThisAddIn.Model}") ? ( (c.Replies.Count == 0) || (c.Replies.Count > 0 && c.Replies[c.Replies.Count].Author != ThisAddIn.Model) ) : AreRepliesUnbalanced(c.Replies) )
)
comments.Add(c);
return comments;
}
private static bool AreRepliesUnbalanced(Comments replies)
{
int userMentionCount = GetCommentMentionCount($"@{ThisAddIn.Model}", replies);
int aiAnswerCount = GetCommentAuthorCount(ThisAddIn.Model, replies);
return (userMentionCount > aiAnswerCount);
}
private static int GetCommentMentionCount(string mention, Comments comments)
{
int count = 0;
for (int i = 1; i <= comments.Count; i++)
if (comments[i].Range.Text != null && comments[i].Range.Text.Contains(mention)) count++;
return count;
}
private static int GetCommentAuthorCount(string author, Comments comments)
{
int count = 0;
for (int i = 1; i <= comments.Count; i++)
if (comments[i].Author == author) count++;
return count;
}
// Checks replies to comments generated by "Writing Tools->Review" action.
private static IEnumerable<Comment> GetUnansweredAIComments(Comments allComments)
{
List<Comment> comments = new List<Comment>();
foreach (Comment c in allComments)
if (c.Ancestor == null &&
c.Author == ThisAddIn.Model &&
( c.Replies.Count > 0 && c.Replies[c.Replies.Count].Author != ThisAddIn.Model )
)
comments.Add(c);
return comments;
}
public static async Task AddComment(Comments comments, Range range, AsyncCollectionResult<StreamingChatCompletionUpdate> streamingContent)
{
Word.Comment c = comments.Add(range, string.Empty);
c.Author = ThisAddIn.Model;
Word.Range commentRange = c.Range.Duplicate; // Duplicate the range to work with
StringBuilder comment = new StringBuilder();
// Run the comment generation in a background thread
await Task.Run(async () =>
{
Forge.CancelButtonVisibility(true);
try
{
await foreach (var update in streamingContent.WithCancellation(ThisAddIn.CancellationTokenSource.Token))
{
if (ThisAddIn.CancellationTokenSource.IsCancellationRequested)
break;
foreach (var content in update.ContentUpdate)
{
commentRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd); // Move to the end of the range
commentRange.Text = content.Text; // Append new text
commentRange = c.Range.Duplicate; // Update the range to include the new text
comment.Append(content.Text);
}
}
}
finally
{
Forge.CancelButtonVisibility(false);
}
c.Range.Text = WordMarkdown.RemoveMarkdownSyntax(comment.ToString());
});
}
}
}