-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1127 lines (906 loc) · 36.6 KB
/
Copy pathProgram.cs
File metadata and controls
1127 lines (906 loc) · 36.6 KB
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//Ignore Spelling: ollama json codellama mixtral yyyy dev codebase
using LocalAIClient.Models;
using LocalAIClient.Services;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace LocalAIClient
{
public static class Program
{
private static RetrievalService retrievalService = new RetrievalService();
private static PromptOrchestrationService promptService = new PromptOrchestrationService();
//Active project variable to maintain context across the application.
//This allows us to keep separate indexes, memories, and summaries for
//different codebases, improving relevance and organization.
private static string? activeProject;
private static string repoPath = "";
private static string indexPath = "";
private static string vectorPath = "";
private static string memoryPath = "";
private static string summaryPath = "";
private static readonly HttpClient http = new HttpClient
{
Timeout = TimeSpan.FromMinutes(10)
};
private static readonly int MaxConversationMessages = 50;
private static LoggingService loggingService = new LoggingService();
private static async Task Main()
{
Console.WriteLine("Select mode:");
Console.WriteLine("1 = Chat");
Console.WriteLine("2 = Index code");
Console.Write("Choice: ");
string? mode = Console.ReadLine();
//Add active project selection. This allows us to maintain
//separate indexes and memories for different codebases, improving
//relevance and organisation.
Console.Write("Repository path: ");
repoPath = Console.ReadLine()!;
if (string.IsNullOrWhiteSpace(repoPath) || !Directory.Exists(repoPath))
{
Console.WriteLine("Invalid repository path.");
return;
}
// Automatically derive project name
activeProject = new DirectoryInfo(repoPath).Name;
indexPath = $@"I:\AI\indexes\{activeProject}";
vectorPath = $@"I:\AI\indexes\vectors\{activeProject}";
memoryPath = $@"I:\AI\memory\{activeProject}\conversation.json";
summaryPath = $@"I:\AI\memory\{activeProject}\summaries.json";
Console.WriteLine($"Active project: {activeProject}");
Console.WriteLine($"RepoPath: {repoPath}");
Console.WriteLine($"IndexPath: {indexPath}");
Console.WriteLine($"VectorPath: {vectorPath}");
Console.WriteLine($"MemoryPath: {memoryPath}");
Console.WriteLine($"SummaryPath: {summaryPath}");
//Checks for saved memory. Reloads previous session. Restores conversation continuity.
List<ConversationMessage> conversationHistory;
if (File.Exists(memoryPath))
{
string memoryJson =
File.ReadAllText(memoryPath);
conversationHistory =
JsonSerializer.Deserialize<
List<ConversationMessage>>
(memoryJson)
?? new List<ConversationMessage>();
Console.WriteLine(
$"Loaded memory: {conversationHistory.Count} messages");
}
else
{
conversationHistory =
new List<ConversationMessage>();
}
if (mode == "1")
{
Console.WriteLine("Local AI Client");
Console.WriteLine("Models: mistral | codellama:13b | mixtral | qwen2.5:3b");
Console.WriteLine("Type 'exit' to quit\n");
while (true)
{
Console.Write("Prompt: ");
var userInput = Console.ReadLine();
if (userInput == "exit") break;
var suggestedModel = SuggestModel(userInput);
Console.WriteLine($"Suggested model: {suggestedModel}");
Console.Write("Model (press Enter to accept suggestion): ");
var modelInput = Console.ReadLine();
if (modelInput == "exit") break;
//model fallback
var model = string.IsNullOrWhiteSpace(modelInput)
? suggestedModel
: modelInput;
Console.WriteLine($"Using model: {model}");
//Save user messages.
conversationHistory.Add(new ConversationMessage
{
Role = "user",
Content = userInput
});
if (conversationHistory.Count > MaxConversationMessages)
{
conversationHistory =
conversationHistory
.TakeLast(MaxConversationMessages)
.ToList();
}
var chunks = await RetrieveHybridChunks(userInput, indexPath, vectorPath);
// DEBUG OUTPUT (Phase 3.6.4.2)
Console.WriteLine("\n--- EXPANDED CONTEXT ---");
foreach (var chunk in chunks)
{
Console.WriteLine(chunk.Substring(0, Math.Min(150, chunk.Length)));
Console.WriteLine("------");
}
int indexedFiles = Directory.Exists(indexPath)
? Directory.GetFiles(indexPath, "*.txt").Length
: 0;
Console.WriteLine($"Files indexed: {indexedFiles}");
//This prevents worst case hallucination.
if (chunks.Count == 0)
{
Console.WriteLine("\n--- RESPONSE ---");
Console.WriteLine("No relevant context found in codebase.");
Console.WriteLine();
continue;
}
string context = BuildSmartContext(chunks);
Console.WriteLine($"\nContext size: {context.Length} chars");
Console.WriteLine($"Chunks used: {chunks.Count}");
/*
* Once we introduce RAG:
* The RAG prompt becomes the real prompt
* So fullPrompt is simply:
* RAG wrapper + your user request
*/
string basePrompt = userInput;
//Build conversation history text.
string conversationText = BuildConversationHistory(conversationHistory, userInput);
Console.WriteLine($"Memory category: {CategorizeMessage(userInput)}");//category diagnostics
Console.WriteLine($"\nMemory context size: {conversationText.Length}");//memory diagnostics
//Inject summaries into prompt.
string summaryText = LoadRecentSummaries(summaryPath);
string fullPrompt = promptService.BuildPrompt(
userInput,
context,
conversationText,
summaryText,
activeProject,
model);
var request = new
{
model = model,
prompt = fullPrompt,
stream = false
};
string json = JsonSerializer.Serialize(request);
try
{
HttpResponseMessage response = await http.PostAsync(
"http://localhost:11434/api/generate",
new StringContent(json, Encoding.UTF8, "application/json")
);
if (!response.IsSuccessStatusCode)
{
throw new Exception(
$"Ollama generate failed: {(int)response.StatusCode} {response.ReasonPhrase}");
}
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine("DEBUG: Raw Ollama response:");
Console.WriteLine(result);
if (string.IsNullOrWhiteSpace(result))
{
throw new Exception("Empty response from Ollama generate API.");
}
JsonNode? jsonNode;
try
{
jsonNode = JsonNode.Parse(result);
}
catch (Exception ex)
{
throw new Exception(
$"Failed to parse generate response: {ex.Message}");
}
string? responseText = jsonNode?["response"]?.ToString();
responseText ??= "No response returned.";
//Save assistant responses.
conversationHistory.Add(new ConversationMessage
{
Role = "assistant",
Content = responseText ?? ""
});
const int maxMessages = 50;
if (conversationHistory.Count > maxMessages)
{
conversationHistory =
conversationHistory
.TakeLast(maxMessages)
.ToList();
}
SaveConversationHistory(conversationHistory, memoryPath);//Save memory after each assistant response.
//Auto-generate summaries periodically.
//Every 10 messages: generates compressed summary, persists summary to disk,
//creates long-term conversational abstraction.
if (conversationHistory.Count % 10 == 0)
{
string summary =
GenerateConversationSummary(
conversationHistory);
SaveConversationSummary(
summary,
summaryPath);
Console.WriteLine(
"\nConversation summary created.");
}
Console.WriteLine("\n--- RESPONSE ---");
Console.WriteLine(responseText);
//Hallucination warning
if (LooksLikeHallucination(responseText))
{
Console.WriteLine("⚠️ Warning: response may contain speculation.");
}
Console.WriteLine();
Console.WriteLine("DEBUG: Writing chat log...");
loggingService.Log(activeProject, model, fullPrompt, responseText ?? "");
}
catch (Exception ex)
{
Console.WriteLine($"ERROR: {ex}");
}
}
}
if (mode == "2")
{
if (Directory.Exists(indexPath))
{
Directory.Delete(indexPath, true);
}
if (Directory.Exists(vectorPath))
{
Directory.Delete(vectorPath, true);
}
List<string> files = GetCodeFiles(repoPath);
int fileCounter = 0;
Console.WriteLine($"Indexing project: {activeProject}");
foreach (var file in files)
{
string content;
try
{
content = File.ReadAllText(file);
}
catch
{
continue;
}
var chunks = ChunkFile(content);
for (int i = 0; i < chunks.Count; i++)
{
var chunkContent = chunks[i];
//
// Save raw chunk
//
var fileName = $"file{fileCounter}_{i}.txt";
var fullPath = Path.Combine(indexPath, fileName);
//Add embedding generation to indexing mode
Directory.CreateDirectory(indexPath);
var enrichedChunk = $"""
FILE: {Path.GetFileName(file)}
PATH: {file}
{chunkContent}
""";
File.WriteAllText(fullPath, enrichedChunk);
//
// Generate embedding
//
var embeddingService = new EmbeddingService();
var embedding = await embeddingService.GenerateEmbedding(chunkContent);
Console.WriteLine($"Embedding size: {embedding.Length}");
//
// Create vector record, indexing pipeline.
//
var record = new EmbeddingRecord
{
FileName = Path.GetFileName(file),
FilePath = file,
ProjectName = new DirectoryInfo(repoPath).Name,
ChunkIndex = i,
Content = chunkContent,
Embedding = embedding
};
Directory.CreateDirectory(vectorPath);
var jsonPath = Path.Combine(
vectorPath,
$"{Path.GetFileNameWithoutExtension(fileName)}.json"
);
var recordJson = JsonSerializer.Serialize(
record,
new JsonSerializerOptions
{
WriteIndented = true
});
File.WriteAllText(jsonPath, recordJson);
Console.WriteLine($"Indexed chunk: {fileName}");
}
fileCounter++;
}
Console.WriteLine("Indexing complete.");
}
}
// A suggestion function.
private static string SuggestModel(string userInput)
{
var input = userInput.ToLower();
if (input.Contains("c#") || input.Contains("code") || input.Contains("class"))
return "codellama:13b";
if (input.Contains("design") || input.Contains("architecture") || input.Contains("analysis"))
return "mixtral";
return "mistral";
}
//Build simple file scanner.
private static List<string> GetCodeFiles(string rootPath)
{
var extensions = new[]
{
".cs",
".js",
".ts",
".tsx",
".jsx",
".html",
".css",
".cpp",
".h",
".hpp",
".py",
".java"
};
var ignoredFolders = new[]
{
"\\bin\\",
"\\obj\\",
"\\node_modules\\",
"\\dist\\",
"\\build\\",
"\\packages\\",
"\\wwwroot\\lib\\",
"\\.git\\",
"\\coverage\\",
"\\vendor\\"
};
return Directory
.GetFiles(rootPath, "*.*", SearchOption.AllDirectories)
.Where(f =>
extensions.Contains(
Path.GetExtension(f),
StringComparer.OrdinalIgnoreCase))
.Where(f =>
!ignoredFolders.Any(ignore =>
f.Contains(ignore,
StringComparison.OrdinalIgnoreCase)))
.ToList();
}
//Read and chunk files.
private static List<string> ChunkFile(string content, int maxChunkSize = 1500)
{
List<string> chunks = new List<string>();
string[] lines = content.Split('\n');
StringBuilder current = new StringBuilder();
foreach (var line in lines)
{
//
// Hard-stop huge lines
//
var safeLine = line.Length > 300
? line.Substring(0, 300)
: line;
//
// If next line exceeds chunk size,
// finalize current chunk
//
if (current.Length + safeLine.Length > maxChunkSize)
{
if (current.Length > 0)
{
chunks.Add(current.ToString());
current.Clear();
}
}
current.AppendLine(safeLine);
}
//
// Final chunk
//
if (current.Length > 0)
{
chunks.Add(current.ToString());
}
return chunks;
}
//Basic hallucination detection (lightweight)
private static bool LooksLikeHallucination(string response)
{
if (response == null) return true;
var text = response.ToLower();
return text.Contains("likely") ||
text.Contains("probably") ||
text.Contains("it seems") ||
text.Contains("typically");
}
//Extract symbols from retrieved chunks
private static List<string> ExtractSymbols(List<string> chunks)
{
var symbols = new HashSet<string>();
foreach (var chunk in chunks)
{
var lines = chunk.Split('\n');
foreach (var line in lines)
{
// class names
if (line.Contains("class "))
{
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var index = Array.IndexOf(parts, "class");
if (index >= 0 && index + 1 < parts.Length)
symbols.Add(parts[index + 1]);
}
// service/interface hints
if (line.Contains("Service") || line.Contains("Controller"))
{
var words = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
foreach (var w in words)
{
if (w.EndsWith("Service") || w.EndsWith("Controller"))
symbols.Add(w);
}
}
}
}
return symbols.ToList();
}
//Second-pass retrieval
private static List<string> ExpandContext(List<string> initialChunks, string indexPath, int maxExpanded = 5)
{
var symbols = ExtractSymbols(initialChunks);
var files = Directory.GetFiles(indexPath, "*.txt");
var scored = new List<(string content, int score)>();
foreach (var file in files)
{
var content = File.ReadAllText(file);
int score = 0;
foreach (var symbol in symbols)
{
// direct symbol match
if (content.Contains(symbol, StringComparison.OrdinalIgnoreCase))
score += 2;
// stronger boost for class definitions
if (content.Contains($"class {symbol}", StringComparison.OrdinalIgnoreCase))
score += 4;
// service usage
if (content.Contains($"{symbol}(", StringComparison.OrdinalIgnoreCase))
score += 1;
}
if (score > 0)
{
scored.Add((content, score));
}
}
List<string> selected = scored
.OrderByDescending(x => x.score)
.Take(maxExpanded)
.Select(x => x.content)
.ToList();
// ensure original chunks always survive
foreach (var chunk in initialChunks)
{
if (!selected.Contains(chunk))
selected.Insert(0, chunk);
}
return selected.Distinct().ToList();
}
//Cosine similarity function. Measures how similar two meanings are.
private static double CosineSimilarity(float[] a, float[] b)
{
double dot = 0;
double magA = 0;
double magB = 0;
for (int i = 0; i < a.Length; i++)
{
dot += a[i] * b[i];
magA += a[i] * a[i];
magB += b[i] * b[i];
}
if (magA == 0 || magB == 0)
{
return 0;
}
return dot / (Math.Sqrt(magA) * Math.Sqrt(magB));
}
//Create semantic retrieval method.
private static async Task<List<string>> RetrieveSemanticChunks(
string query,
string vectorPath,
int maxChunks = 3)
{
var embeddingService = new EmbeddingService();
//
// Generate query embedding
//
var queryEmbedding =
await embeddingService.GenerateEmbedding(query);
if (!Directory.Exists(vectorPath))
{
return new List<string>();
}
//
// Load vector files
//
var files = Directory.GetFiles(vectorPath, "*.json");
//semantic retrieval output
var scored = new List<(EmbeddingRecord record, double score)>();
foreach (var file in files)
{
var json = File.ReadAllText(file);
var record = JsonSerializer.Deserialize<EmbeddingRecord>(json);
if (record == null || record.Embedding == null)
continue;
//
// Compare vector similarity
//
var similarity =
CosineSimilarity(queryEmbedding, record.Embedding);
scored.Add((record, similarity));
}
//
// Highest similarity first
//
var results = scored
.OrderByDescending(x => x.score)
.Take(maxChunks)
.Select(x =>
$"""
FILE: {x.record.FileName}
PROJECT: {x.record.ProjectName}
CHUNK: {x.record.ChunkIndex}
{x.record.Content}
""")
.ToList();
//
// DEBUG
//
Console.WriteLine("\n--- SEMANTIC MATCHES ---");
foreach (var result in results)
{
Console.WriteLine(
result.Substring(0, Math.Min(200, result.Length)));
Console.WriteLine("------");
}
return results;
}
//Create hybrid retrieval method.
private static async Task<List<string>> RetrieveHybridChunks(
string query,
string indexPath,
string vectorPath,
int maxChunks = 25)
{
if (query.Contains("all controllers", StringComparison.OrdinalIgnoreCase))
{
maxChunks = 50;
}
if (query.Contains("list", StringComparison.OrdinalIgnoreCase))
{
maxChunks = 40;
}
//
// Keyword retrieval
//
var keywordChunks = retrievalService
.RetrieveRelevantChunks(query, indexPath, maxChunks);
//
// Semantic retrieval
//
var semanticChunks =
await RetrieveSemanticChunks(query, vectorPath, maxChunks);
//
// Merge
//
var merged = keywordChunks
.Concat(semanticChunks)
.Distinct()
.ToList();
//
// Simple re-ranking:
// prefer chunks containing query terms
//
var reranked = merged
.Select(chunk =>
{
int score = 0;
var words = query
.Split(' ', StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
{
if (chunk.Contains(
word,
StringComparison.OrdinalIgnoreCase))
{
score++;
}
}
return new
{
Content = chunk,
Score = score
};
})
.OrderByDescending(x => x.Score)
.ThenByDescending(x => x.Content.Length)
.Take(maxChunks)
.Select(x => x.Content)
.ToList();
//
// DEBUG
//
Console.WriteLine("\n--- HYBRID RETRIEVAL ---");
foreach (var chunk in reranked)
{
Console.WriteLine(
chunk.Substring(
0,
Math.Min(200, chunk.Length)));
Console.WriteLine("------");
}
return reranked;
}
//Chunk compression helper.
private static string CompressChunk(string content, int maxLength = 1200)
{
if (content.Length <= maxLength)
return content;
return content.Substring(0, maxLength)
+ "\n\n...[TRUNCATED]";
}
private static string BuildSmartContext(List<string> chunks, int maxContextLength = 12000)
{
var builder = new StringBuilder();
var usedFiles = new HashSet<string>();
foreach (var chunk in chunks)
{
//
// Avoid duplicate files dominating context
//
var lines = chunk.Split('\n');
var fileLine = lines
.FirstOrDefault(l => l.StartsWith("FILE:"));
if (fileLine != null)
{
if (usedFiles.Contains(fileLine))
continue;
usedFiles.Add(fileLine);
}
//
// Compress large chunks
//
var compressed = CompressChunk(chunk);
//
// Respect context budget
//
if (builder.Length + compressed.Length
> maxContextLength)
{
break;
}
builder.AppendLine(compressed);
builder.AppendLine("\n---\n");
}
return builder.ToString();
}
//Conversation history builder. This constructs a relevant subset of past
//conversation to inject into the prompt, providing context and continuity
//while respecting token limits. It uses relevance scoring to select the most
//pertinent messages based on the current user query.
private static string BuildConversationHistory(
List<ConversationMessage> history,
string currentQuery,
int maxMessages = 6)
{
List<ConversationMessage> relevantMessages = GetRelevantCategoryMemory(currentQuery, history, maxMessages);
StringBuilder builder = new StringBuilder();
foreach (var message in relevantMessages)
{
builder.AppendLine($"{message.Role.ToUpper()}:");
builder.AppendLine(message.Content);
builder.AppendLine();
}
//Prevent oversized memory injection
const int maxMemoryChars = 4000;
if (builder.Length > maxMemoryChars)
{
return builder.ToString()
.Substring(0, maxMemoryChars);
}
return builder.ToString();
}
//Create memory save helper.
private static void SaveConversationHistory(
List<ConversationMessage> history,
string memoryPath)
{
Directory.CreateDirectory(
Path.GetDirectoryName(memoryPath)!);
//IMPORTANT: memory will eventually grow too large (memory trimming).
if (history.Count > MaxConversationMessages)
{
history = history
.TakeLast(MaxConversationMessages)
.ToList();
}
var json = JsonSerializer.Serialize(
history,
new JsonSerializerOptions
{
WriteIndented = true
});
File.WriteAllText(memoryPath, json);
}
//Memory relevance scorer.
private static int ScoreMemoryRelevance(
string query,
ConversationMessage message)
{
int score = 0;
var queryWords = query
.ToLower()
.Split(
[' ', '\n', '\r', '\t', '.', ',', ':', ';', '(', ')'],
StringSplitOptions.RemoveEmptyEntries)
.Where(w => w.Length > 2)
.Distinct();
foreach (var word in queryWords)
{
if (message.Content.Contains(
word,
StringComparison.OrdinalIgnoreCase))
{
score++;
}
}
return score;
}
//Create summary generation helper. This creates lightweight conversational abstraction instead of storing only raw chat logs.
public static string GenerateConversationSummary(List<ConversationMessage> history, int maxMessages = 20)
{
List<ConversationMessage> recent = history
.TakeLast(maxMessages)
.ToList();
StringBuilder builder = new StringBuilder();
builder.AppendLine(
"Conversation topics discussed:");
foreach (ConversationMessage message in recent)
{
if (message.Role == "user")
{
builder.AppendLine(
$"- {message.Content}");
}
}
return builder.ToString();
}
//Create summary persistence helper. This allows us to maintain a high-level
//overview of past conversations without needing to read through entire chat logs.
public static void SaveConversationSummary(string summary, string summaryPath)
{
List<ConversationSummary> summaries;
if (File.Exists(summaryPath))
{
string json =
File.ReadAllText(summaryPath);
summaries =
JsonSerializer.Deserialize<
List<ConversationSummary>>(json)
?? new();
}
else
{
summaries = new();
}
summaries.Add(
new ConversationSummary
{
CreatedAt = DateTime.Now,
Summary = summary
});
string output =
JsonSerializer.Serialize(
summaries,
new JsonSerializerOptions
{
WriteIndented = true
});
Directory.CreateDirectory(Path.GetDirectoryName(summaryPath)!);