Skip to content

Commit 06382fb

Browse files
committed
Fixes RAG system
1 parent 53d0141 commit 06382fb

15 files changed

+874
-480
lines changed

Forge.cs

Lines changed: 17 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using System;
22
using System.ClientModel;
33
using System.Collections.Generic;
4-
using System.IO;
54
using System.Linq;
65
using System.Text;
76
using System.Threading;
@@ -10,7 +9,6 @@
109
using Microsoft.Office.Tools;
1110
using Microsoft.Office.Tools.Ribbon;
1211
using OpenAI.Chat;
13-
using OpenAI.Models;
1412
using Task = System.Threading.Tasks.Task;
1513
using Word = Microsoft.Office.Interop.Word;
1614

@@ -90,6 +88,7 @@ private void ModelListDropDown_SelectionChanged(object sender, RibbonControlEven
9088
try
9189
{
9290
ThisAddIn.Model = ModelListDropDown.SelectedItem.Label;
91+
ThisAddIn.ContextLength = RAGControl.GetContextLength(ThisAddIn.Model);
9392
UpdateCheckbox();
9493
}
9594
catch (Exception ex)
@@ -178,19 +177,27 @@ private async void WritingToolsGallery_ButtonClick(object sender, RibbonControlE
178177
private static async Task ReviewButton_Click()
179178
{
180179
Word.Paragraphs paragraphs = Globals.ThisAddIn.Application.ActiveDocument.Paragraphs;
181-
182180
const string prompt = "As an expert writing assistant, suggest specific improvements to the paragraph, focusing on clarity, coherence, structure, grammar, and overall effectiveness. Ensure that your suggestions are detailed and aimed at improving the paragraph within the context of the entire Document.";
181+
182+
bool hasCommented = false;
183183
if (Globals.ThisAddIn.Application.Selection.End - Globals.ThisAddIn.Application.Selection.Start > 0)
184184
{
185185
await AddComment(Globals.ThisAddIn.Application.ActiveDocument.Comments, Globals.ThisAddIn.Application.Selection.Range, Review(paragraphs, Globals.ThisAddIn.Application.Selection.Range, prompt));
186+
hasCommented = true;
186187
}
187188
else
188189
{
189190
foreach (Word.Paragraph p in paragraphs)
190191
// It isn't a paragraph if it doesn't contain a full stop.
191192
if (p.Range.Text.Contains('.'))
193+
{
192194
await AddComment(Globals.ThisAddIn.Application.ActiveDocument.Comments, p.Range, Review(paragraphs, p.Range, prompt));
195+
hasCommented = true;
196+
}
197+
193198
}
199+
if (!hasCommented)
200+
MessageBox.Show("Review complete!", "Action Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
194201
}
195202

196203
private static async Task ProofreadButton_Click()
@@ -215,7 +222,11 @@ private static async Task AnalyzeText(string systemPrompt, string userPrompt)
215222
var range = (selectionRange.End - selectionRange.Start > 0) ? selectionRange : throw new InvalidRangeException("No text is selected for analysis!");
216223

217224
ChatClient client = new ChatClient(ThisAddIn.Model, ThisAddIn.ApiKey, ThisAddIn.ClientOptions);
218-
var streamingAnswer = client.CompleteChatStreamingAsync(new SystemChatMessage(systemPrompt), new UserChatMessage(@$"{userPrompt}: {range.Text}"));
225+
var streamingAnswer = client.CompleteChatStreamingAsync(
226+
new List<ChatMessage>() { new SystemChatMessage(systemPrompt), new UserChatMessage(@$"{userPrompt}: {range.Text}") },
227+
new ChatCompletionOptions() { MaxTokens = ThisAddIn.ContextLength },
228+
ThisAddIn.CancellationTokenSource.Token
229+
);
219230
range.Delete();
220231
await AddStreamingContentToRange(streamingAnswer, range);
221232
Globals.ThisAddIn.Application.Selection.SetRange(range.Start, range.End);
@@ -250,14 +261,6 @@ private void UpdateCheckbox()
250261
DefaultCheckBox.Checked = (Properties.Settings.Default.DefaultModel == ThisAddIn.Model);
251262
}
252263

253-
public static List<string> GetModels(ModelClient model)
254-
{
255-
List<string> models = new List<string>();
256-
foreach (OpenAIModelInfo info in model.GetModels().Value)
257-
models.Add(info.Id);
258-
return models;
259-
}
260-
261264
public static async Task AddComment(Word.Comments comments, Word.Range range, AsyncCollectionResult<StreamingChatCompletionUpdate> streamingContent)
262265
{
263266
Word.Comment c = comments.Add(range, string.Empty);
@@ -286,31 +289,9 @@ await Task.Run(async () =>
286289

287290
private static AsyncCollectionResult<StreamingChatCompletionUpdate> Review(Word.Paragraphs context, Word.Range p, string prompt)
288291
{
289-
const int promptWordLen = 50;
290292
var docRange = Globals.ThisAddIn.Application.ActiveDocument.Range();
291-
int documentLength = (int)(docRange.Words.Count * 1.3);
292-
string allText = docRange.Text;
293-
294-
if (ThisAddIn.ContextLength - documentLength - p.Words.Count - promptWordLen - (int)(ThisAddIn.ContextLength * 0.3) < 0)
295-
{
296-
HyperVectorDB.HyperVectorDB DB = new HyperVectorDB.HyperVectorDB(ThisAddIn.Embedder, Path.GetTempPath());
297-
foreach (Word.Paragraph paragraph in context)
298-
{
299-
if (paragraph.Range == p) continue;
300-
var chunks = RAGControl.SplitString(paragraph.Range.Text, RAGControl.CHUNK_LEN);
301-
foreach (var chunk in chunks)
302-
DB.IndexDocument(chunk);
303-
}
304-
var result = DB.QueryCosineSimilarity(p.Text, 3);
305-
StringBuilder ragContext = new StringBuilder();
306-
foreach (var doc in result.Documents)
307-
ragContext.AppendLine(doc.DocumentString);
308-
allText = ragContext.ToString();
309-
}
310-
UserChatMessage userPrompt = new UserChatMessage($@"Document Content: ""{RAGControl.SubstringTokens(allText, (int)(ThisAddIn.ContextLength * 0.4))}""{Environment.NewLine}RAG Context: ""{ThisAddIn.RagControl.GetRAGContext(p.Text, (int)(ThisAddIn.ContextLength * 0.3))}""{Environment.NewLine}Please review the following paragraph extracted from the Document: ""{RAGControl.SubstringTokens(p.Text, (int)(ThisAddIn.ContextLength * 0.2))}""{Environment.NewLine}{prompt}");
311-
312-
ChatClient client = new ChatClient(ThisAddIn.Model, ThisAddIn.ApiKey, ThisAddIn.ClientOptions);
313-
return client.CompleteChatStreamingAsync(new List<ChatMessage> { SystemPrompt, userPrompt }, null, ThisAddIn.CancellationTokenSource.Token);
293+
UserChatMessage commentPrompt = new UserChatMessage($@"Please review the following paragraph extracted from the Document: ""{RAGControl.SubstringTokens(p.Text, (int)(ThisAddIn.ContextLength * 0.2))}""{Environment.NewLine}{prompt}");
294+
return RAGControl.AskQuestion(SystemPrompt, new List<UserChatMessage> { commentPrompt }, docRange);
314295
}
315296
}
316297
}

GenerateUserControl.Designer.cs

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

GenerateUserControl.cs

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,7 @@
11
using System;
2-
using System.ClientModel;
32
using System.Collections.Generic;
4-
using System.IO;
5-
using System.Runtime.Remoting.Contexts;
6-
using System.Text;
7-
using System.Threading.Tasks;
83
using System.Windows.Forms;
9-
using HyperVectorDB.Embedder;
104
using OpenAI.Chat;
11-
using Word = Microsoft.Office.Interop.Word;
125

136
namespace TextForge
147
{
@@ -39,7 +32,12 @@ private async void GenerateButton_Click(object sender, EventArgs e)
3932
* Then, it won't affect where the text is placed.
4033
*/
4134
var rangeBeforeChat = Globals.ThisAddIn.Application.Selection.Range;
42-
var streamingAnswer = AskQuestion(_systemPrompt, Globals.ThisAddIn.Application.ActiveDocument.Range(), textBoxContent);
35+
var docRange = Globals.ThisAddIn.Application.ActiveDocument.Range();
36+
var streamingAnswer = RAGControl.AskQuestion(
37+
_systemPrompt,
38+
new List<UserChatMessage> { new UserChatMessage(textBoxContent) },
39+
docRange
40+
);
4341

4442
// Clear any selected text by the user
4543
if (rangeBeforeChat.End - rangeBeforeChat.Start > 0)
@@ -62,16 +60,13 @@ private async void GenerateButton_Click(object sender, EventArgs e)
6260
}
6361
}
6462

65-
public static AsyncCollectionResult<StreamingChatCompletionUpdate> AskQuestion(SystemChatMessage systemPrompt, Word.Range context, string prompt)
63+
private void PromptTextBox_KeyDown(object sender, KeyEventArgs e)
6664
{
67-
string document = (Globals.ThisAddIn.Application.ActiveDocument.Words.Count * 1.4 > ThisAddIn.ContextLength * 0.4) ? RAGControl.GetWordDocumentAsRAG(prompt, context) : context.Text;
68-
69-
// 0.1 of context length leftover to account for UserChatMessage and other stuff
70-
SystemChatMessage systemPromptBounded = new SystemChatMessage(RAGControl.SubstringTokens(systemPrompt.Content[0].Text, (int)(ThisAddIn.ContextLength * 0.1)));
71-
UserChatMessage fullPrompt = new UserChatMessage($@"{RAGControl.SubstringTokens(prompt, (int) (ThisAddIn.ContextLength * 0.2))}{Environment.NewLine}RAG Context: ""{ThisAddIn.RagControl.GetRAGContext(prompt, (int)(ThisAddIn.ContextLength * 0.2))}""{Environment.NewLine}Document Content: ""{RAGControl.SubstringTokens(document, (int)(ThisAddIn.ContextLength * 0.4))}""");
72-
73-
ChatClient client = new ChatClient(ThisAddIn.Model, ThisAddIn.ApiKey, ThisAddIn.ClientOptions);
74-
return client.CompleteChatStreamingAsync(new List<ChatMessage>() { systemPromptBounded, fullPrompt }, null, ThisAddIn.CancellationTokenSource.Token);
65+
if (e.Control && e.KeyCode == Keys.Enter)
66+
{
67+
e.SuppressKeyPress = true;
68+
this.GenerateButton.PerformClick();
69+
}
7570
}
7671
}
7772
}

0 commit comments

Comments
 (0)