-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLlmService.cs
More file actions
1299 lines (1151 loc) · 65 KB
/
LlmService.cs
File metadata and controls
1299 lines (1151 loc) · 65 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
using System;
using System.Configuration;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
// Using statements for Betalgo.Ranul.OpenAI
using Betalgo.Ranul.OpenAI; // For OpenAIService, OpenAIOptions
using System.Text.Json; // Added for System.Text.Json
using System.Text.Json.Serialization; // Added for JsonPropertyName attributes
using Betalgo.Ranul.OpenAI.Interfaces; // For IOpenAIService
using Betalgo.Ranul.OpenAI.ObjectModels; // For Models (e.g., Models.Gpt_3_5_Turbo)
using Betalgo.Ranul.OpenAI.ObjectModels.RequestModels; // For ChatCompletionCreateRequest, ChatMessage
namespace TimeTask
{
public enum ClarityStatus
{
Clear,
NeedsClarification,
Unknown
}
public enum DecompositionStatus
{
Sufficient,
NeedsDecomposition,
Unknown
}
public class ProposedDailyTask
{
[JsonPropertyName("day")]
public int Day { get; set; }
[JsonPropertyName("task_description")]
public string TaskDescription { get; set; }
[JsonPropertyName("quadrant")]
public string Quadrant { get; set; }
[JsonPropertyName("estimated_time")]
public string EstimatedTime { get; set; }
}
public class LlmLearningMilestone
{
[JsonPropertyName("stage")]
public int Stage { get; set; }
[JsonPropertyName("title")]
public string Title { get; set; }
[JsonPropertyName("description")]
public string Description { get; set; }
[JsonPropertyName("estimated_time")]
public string EstimatedTime { get; set; }
[JsonPropertyName("is_completed")]
public bool IsCompleted { get; set; }
}
public class LlmSkillRecommendation
{
[JsonPropertyName("skill_id")]
public string SkillId { get; set; }
[JsonPropertyName("title")]
public string Title { get; set; }
[JsonPropertyName("why")]
public string Why { get; set; }
[JsonPropertyName("next_step")]
public string NextStep { get; set; }
[JsonPropertyName("confidence")]
public double Confidence { get; set; }
}
public class LlmService : ILlmService
{
private IOpenAIService _openAiService;
private string _apiKey;
private string _apiBaseUrl; // New field for API Base URL
private string _modelName; // New field for Model Name
private TimeSpan _httpClientTimeout = TimeSpan.FromSeconds(120); // Default value
private const string PlaceholderApiKey = "YOUR_API_KEY_GOES_HERE";
private const string DefaultModelName = "gpt-3.5-turbo"; // Default model
// Prompts remain the same
private const string PrioritizationSystemPrompt =
"Analyze the following task description and determine its importance and urgency. " +
"Return your answer strictly in the format: \"Importance: [High/Medium/Low], Urgency: [High/Medium/Low]\". " +
"Do not add any other text, explanations, or elaborations. Just the single line in the specified format.\n" +
"For example, if the task is 'Fix critical login bug', you should respond with: \"Importance: High, Urgency: High\".\n" +
"Task: ";
private const string ClarityAnalysisSystemPrompt =
"Analyze the following task description for clarity, specificity, and actionability. " +
"Respond in the following format ONLY:\n" +
"Status: [Clear/NeedsClarification]\n" +
"Question: [If Status is NeedsClarification, provide a concise question to the user to get the necessary details. Otherwise, write N/A]\n" +
"Examples:\n" +
"Input Task: Organize event.\n" +
"Status: NeedsClarification\n" +
"Question: What kind of event is it and what are the key objectives or desired outcomes?\n\n" +
"Input Task: Draft a project proposal for Q3 by Friday.\n" +
"Status: Clear\n" +
"Question: N/A\n\n" +
"Input Task: ";
private const string TaskDecompositionSystemPrompt =
"Analyze the following task description. If the task is too broad or complex, break it down into 2-5 actionable sub-tasks. " +
"If the task is already granular and actionable, indicate that it is sufficient. " +
"Respond in the following format ONLY:\n" +
"Status: [Sufficient/NeedsDecomposition]\n" +
"Subtasks: [If NeedsDecomposition, provide a list of sub-tasks, each on a new line, optionally prefixed with '-' or '*'. If Sufficient, write N/A.]\n" +
"Examples:\n" +
"Input Task: Plan company retreat.\n" +
"Status: NeedsDecomposition\n" +
"Subtasks:\n" +
"- Define budget and objectives\n" +
"- Research and select venue\n" +
"- Plan agenda and activities\n" +
"- Coordinate logistics (transport, accommodation)\n\n" +
"Input Task: Email John about the meeting report.\n" +
"Status: Sufficient\n" +
"Subtasks: N/A\n\n" +
"Input Task: ";
private const string TaskReminderSystemPrompt =
"You are an assistant helping a user review a task. The task is described below, and you're given how old it is (time since last modification). " +
"Generate a brief, friendly, encouraging reminder about the task. " +
"Then, provide 2-3 actionable, concise suggestions for the user. " +
"Respond in the following format ONLY:\n" +
"Reminder: [Generated reminder text]\n" +
"Suggestion1: [Text for suggestion 1]\n" +
"Suggestion2: [Text for suggestion 2]\n" +
"(Optional) Suggestion3: [Text for suggestion 3]\n\n" +
"Task Description: {taskDescription}\n" +
"Task Age: {taskAge}\n\n" +
"Example output:\n" +
"Reminder: Just checking in on the '{taskDescription}' task. It's been about {taskAge}. How's it going?\n" +
"Suggestion1: Ready to complete it now?\n" +
"Suggestion2: Need to adjust its plan or priority?\n" +
"Suggestion3: Want to break it into smaller pieces?";
private const string ReminderProfileHintTemplate =
"\n\nUser behavior context (local profile, use as soft guidance only):\n{userContext}\n" +
"Adapt tone and suggestions to reduce interruption. Keep one clear next step.";
private const string SkillRecommendationSystemPromptTemplate =
"You are a task execution copilot. Based on the task and context, recommend 1-3 skills that best help the user move forward now. " +
"Allowed skill_id values ONLY: {allowedSkillIds}. " +
"Return ONLY a valid JSON array. Each item must contain: " +
"\"skill_id\", \"title\", \"why\", \"next_step\", \"confidence\" (0 to 1). " +
"Keep title/why/next_step concise and actionable.\n" +
"Task: {taskDescription}\n" +
"Importance: {importance}\n" +
"Urgency: {urgency}\n" +
"InactiveDuration: {inactiveDuration}\n" +
"UserContext: {userContext}";
private const string ConversationTaskExtractPrompt =
"You are an assistant helping a user capture personal action items from a multi-speaker conversation. " +
"Extract ONLY tasks that the user should do. " +
"Return a JSON array of strings. Do not include any extra text.\n" +
"Conversation:\n";
private const string GoalDecompositionSystemPrompt = @"
You are an expert goal planning assistant. Your task is to take a user's long-term goal and a specified duration, and break it down into a series of smaller, actionable daily tasks. For each task, you must also categorize it into one of four quadrants based on its importance and urgency, and provide an estimated time for completion.
The four quadrants are:
1. ""Important & Urgent""
2. ""Important & Not Urgent""
3. ""Not Important & Urgent""
4. ""Not Important & Not Urgent""
The user will provide the goal and duration. You need to generate a plan of daily (or near-daily) tasks that will help the user achieve their goal within the given timeframe.
Respond with a JSON array of task objects. Each object should have the following fields:
- ""task_description"": A string describing the task.
- ""quadrant"": A string representing one of the four quadrant categories (e.g., ""Important & Urgent"").
- ""estimated_time"": A string describing the estimated time to complete the task (e.g., ""1 hour"", ""30 minutes"").
- ""day"": An integer representing the day number in the plan (e.g., 1, 2, 3...). This is relative to the start of the plan.
Example Input from User:
Goal: ""I want to learn Python programming for web development.""
Duration: ""3 months""
Example JSON Output:
[
{
""day"": 1,
""task_description"": ""Set up Python development environment (install Python, VS Code, Git)."",
""quadrant"": ""Important & Urgent"",
""estimated_time"": ""2 hours""
},
{
""day"": 1,
""task_description"": ""Complete Chapter 1 of Python basics tutorial (variables, data types)."",
""quadrant"": ""Important & Not Urgent"",
""estimated_time"": ""1.5 hours""
}
]
Ensure the tasks are logically sequenced and contribute towards the main goal. Distribute tasks reasonably across the duration. For this request, please provide a detailed daily task plan for the **first 2 weeks** only, based on the user's goal of '{userGoal}' (total duration '{userDuration}'). This 2-week plan should be very detailed.
User Input:
Goal: ""{userGoal}""
Duration: ""{userDuration}""
IMPORTANT: Your entire response MUST be a valid JSON array of task objects for the first 2 weeks, starting with '[' and ending with ']'. Do not include any other text, explanations, or markdown formatting outside of this JSON array. Be direct in your JSON output."; // Note the {userGoal} and {userDuration} placeholders.
private const string LearningPlanDecompositionSystemPrompt = @"
You are an expert learning plan assistant. Your task is to take a user's learning subject and goal, along with a specified duration, and break it down into a series of progressive learning milestones. For each milestone, you must provide a title, description, and estimated time for completion.
The user will provide the subject, goal, and duration. You need to generate a structured learning plan with milestones that will help the user achieve their learning goal within the given timeframe.
Respond with a JSON array of milestone objects. Each object should have the following fields:
- ""stage"": An integer representing the stage number in the learning plan (e.g., 1, 2, 3...).
- ""title"": A string title for the milestone.
- ""description"": A string describing what will be learned in this milestone.
- ""estimated_time"": A string describing the estimated time to complete this milestone (e.g., ""2 weeks"", ""1 month"").
- ""is_completed"": A boolean indicating completion status (always false for new plans).
Example Input from User:
Subject: ""Python Programming""
Goal: ""Learn Python for web development""
Duration: ""3 months""
Example JSON Output:
[
{
""stage"": 1,
""title"": ""Python Fundamentals"",
""description"": ""Master Python basics including variables, data types, control flow, functions, and object-oriented programming concepts."",
""estimated_time"": ""3 weeks"",
""is_completed"": false
},
{
""stage"": 2,
""title"": ""Web Development with Flask"",
""description"": ""Learn Flask framework, routing, templates, and building RESTful APIs."",
""estimated_time"": ""4 weeks"",
""is_completed"": false
}
]
Ensure the milestones are logically sequenced and progressively build upon each other. Distribute milestones reasonably across the duration. For this request, please provide a comprehensive learning plan for the subject '{subject}' with the goal '{goal}' (total duration '{duration}').
User Input:
Subject: ""{subject}""
Goal: ""{goal}""
Duration: ""{duration}""
IMPORTANT: Your entire response MUST be a valid JSON array of milestone objects, starting with '[' and ending with ']'. Do not include any other text, explanations, or markdown formatting outside of this JSON array. Be direct in your JSON output."; // Note the {subject}, {goal}, and {duration} placeholders.
public LlmService()
{
LoadLlmConfig(); // Renamed from LoadApiKeyFromConfig
InitializeOpenAiService();
}
// Constructor for dependency injection, typically for testing
internal LlmService(IOpenAIService openAiService, string apiKey, string apiBaseUrl, string modelName)
{
_openAiService = openAiService ?? throw new ArgumentNullException(nameof(openAiService));
_apiKey = apiKey ?? throw new ArgumentNullException(nameof(apiKey));
_apiBaseUrl = apiBaseUrl; // Can be null
_modelName = modelName ?? throw new ArgumentNullException(nameof(modelName));
// Ensure critical fields are not placeholder values if GetCompletionAsync relies on them
if (_apiKey == PlaceholderApiKey)
{
// Or throw, or handle as per service's expectation for injected services.
Console.WriteLine("Warning: LlmService injected with a placeholder API key.");
}
Console.WriteLine($"LlmService: Initialized with injected IOpenAIService. Model: {_modelName}. API Key Loaded: {!string.IsNullOrWhiteSpace(_apiKey) && _apiKey != PlaceholderApiKey}. Base URL: '{_apiBaseUrl ?? "OpenAI Default"}'");
}
public async Task<List<ProposedDailyTask>> DecomposeGoalIntoDailyTasksAsync(string goal, string durationString)
{
if (string.IsNullOrWhiteSpace(goal) || string.IsNullOrWhiteSpace(durationString))
{
Console.WriteLine("Goal or duration string is empty for DecomposeGoalIntoDailyTasksAsync.");
return new List<ProposedDailyTask>();
}
string fullPrompt = GoalDecompositionSystemPrompt
.Replace("{userGoal}", goal)
.Replace("{userDuration}", durationString);
string llmResponse = await GetCompletionAsync(fullPrompt);
Console.WriteLine("LlmService: Raw LLM Response for Goal Decomposition:");
Console.WriteLine(llmResponse);
if (IsErrorResponse(llmResponse))
{
Console.WriteLine($"LLM did not provide a valid response for goal decomposition. Goal: '{goal}'. Response: {llmResponse}");
throw new InvalidOperationException($"LLM API调用失败: {llmResponse}");
}
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true // Handles "task_description" vs "TaskDescription"
};
try
{
// Clean the response if it's wrapped in markdown ```json ... ```
llmResponse = llmResponse.Trim();
if (llmResponse.StartsWith("```json"))
{
llmResponse = llmResponse.Substring(7);
}
if (llmResponse.EndsWith("```"))
{
llmResponse = llmResponse.Substring(0, llmResponse.Length - 3);
}
llmResponse = llmResponse.Trim();
List<ProposedDailyTask> tasks = JsonSerializer.Deserialize<List<ProposedDailyTask>>(llmResponse, options);
if (tasks != null && tasks.Any())
{
Console.WriteLine($"LlmService: Successfully parsed {tasks.Count} tasks. Reviewing for missing details...");
bool foundMissingDetails = false;
for (int i = 0; i < tasks.Count; i++)
{
var taskDetail = tasks[i];
bool hasMissingDescription = string.IsNullOrWhiteSpace(taskDetail.TaskDescription);
bool hasMissingTime = string.IsNullOrWhiteSpace(taskDetail.EstimatedTime);
if (hasMissingDescription || hasMissingTime)
{
foundMissingDetails = true;
Console.WriteLine($"LlmService: Parsed Task #{i + 1} (Day={taskDetail.Day}) has missing details: Description='{taskDetail.TaskDescription}', Quadrant='{taskDetail.Quadrant}', EstimatedTime='{taskDetail.EstimatedTime}'");
}
}
if (!foundMissingDetails)
{
Console.WriteLine("LlmService: All parsed tasks appear to have descriptions and estimated times.");
// Optional: Log first few tasks for confirmation if desired, e.g.:
// Console.WriteLine("LlmService: Logging first few tasks for confirmation (up to 3):");
// foreach (var taskDetail in tasks.Take(3))
// {
// Console.WriteLine($"LlmService: Parsed Task: Day={taskDetail.Day}, Description='{taskDetail.TaskDescription}', Quadrant='{taskDetail.Quadrant}', EstimatedTime='{taskDetail.EstimatedTime}'");
// }
}
}
else if (tasks != null) // tasks is not null but empty, i.e., tasks.Count == 0
{
Console.WriteLine("LlmService: LLM response parsed into an empty list of tasks.");
}
// If tasks is null, it implies a deserialization failure, which should be caught by JsonException handler.
return tasks ?? new List<ProposedDailyTask>();
}
catch (JsonException jsonEx)
{
Console.WriteLine($"Error parsing JSON response for goal decomposition: {jsonEx.Message}. Response was: {llmResponse}");
return new List<ProposedDailyTask>(); // Directly return an empty list
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred during goal decomposition: {ex.Message}. Response was: {llmResponse}");
return new List<ProposedDailyTask>(); // Or throw
}
}
public async Task<List<LlmLearningMilestone>> DecomposeLearningPlanIntoMilestonesAsync(string subject, string goal, string durationString)
{
if (string.IsNullOrWhiteSpace(subject) || string.IsNullOrWhiteSpace(goal) || string.IsNullOrWhiteSpace(durationString))
{
Console.WriteLine("Subject, goal, or duration string is empty for DecomposeLearningPlanIntoMilestonesAsync.");
return new List<LlmLearningMilestone>();
}
string fullPrompt = LearningPlanDecompositionSystemPrompt
.Replace("{subject}", subject)
.Replace("{goal}", goal)
.Replace("{duration}", durationString);
string llmResponse = await GetCompletionAsync(fullPrompt);
Console.WriteLine("LlmService: Raw LLM Response for Learning Plan Decomposition:");
Console.WriteLine(llmResponse);
if (IsErrorResponse(llmResponse))
{
Console.WriteLine($"LLM did not provide a valid response for learning plan decomposition. Subject: '{subject}', Goal: '{goal}'. Response: {llmResponse}");
throw new InvalidOperationException($"LLM API调用失败: {llmResponse}");
}
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
try
{
llmResponse = llmResponse.Trim();
if (llmResponse.StartsWith("```json"))
{
llmResponse = llmResponse.Substring(7);
}
if (llmResponse.EndsWith("```"))
{
llmResponse = llmResponse.Substring(0, llmResponse.Length - 3);
}
llmResponse = llmResponse.Trim();
List<LlmLearningMilestone> milestones = JsonSerializer.Deserialize<List<LlmLearningMilestone>>(llmResponse, options);
if (milestones != null && milestones.Any())
{
Console.WriteLine($"LlmService: Successfully parsed {milestones.Count} milestones.");
foreach (var milestone in milestones)
{
milestone.IsCompleted = false;
}
}
else if (milestones != null)
{
Console.WriteLine("LlmService: LLM response parsed into an empty list of milestones.");
}
return milestones ?? new List<LlmLearningMilestone>();
}
catch (JsonException jsonEx)
{
Console.WriteLine($"Error parsing JSON response for learning plan decomposition: {jsonEx.Message}");
Console.WriteLine($"JSON Path: {jsonEx.Path}, Line: {jsonEx.LineNumber}, Position: {jsonEx.BytePositionInLine}");
Console.WriteLine($"Raw response that failed to parse: {llmResponse}");
return new List<LlmLearningMilestone>();
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred during learning plan decomposition: {ex.Message}");
Console.WriteLine($"Exception type: {ex.GetType().Name}");
Console.WriteLine($"Raw response: {llmResponse}");
return new List<LlmLearningMilestone>();
}
}
internal string FormatTimeSpan(TimeSpan ts)
{
if (ts.TotalDays >= 7)
{
int weeks = (int)(ts.TotalDays / 7);
return $"{weeks} week{(weeks > 1 ? "s" : "")} old";
}
if (ts.TotalDays >= 1)
{
return $"{(int)ts.TotalDays} day{(ts.TotalDays > 1 ? "s" : "")} old";
}
if (ts.TotalHours >= 1)
{
return $"{(int)ts.TotalHours} hour{(ts.TotalHours > 1 ? "s" : "")} old";
}
return "less than an hour old";
}
internal static (string reminder, List<string> suggestions) ParseReminderResponse(string llmResponse)
{
Console.WriteLine($"Parsing LLM reminder response: \"{llmResponse}\"");
var suggestions = new List<string>();
string reminder = string.Empty;
if (string.IsNullOrWhiteSpace(llmResponse))
{
Console.WriteLine("LLM response is null or whitespace. Returning empty reminder and suggestions.");
return (reminder, suggestions);
}
try
{
var reminderRegex = new Regex(@"Reminder\s*:\s*(.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
var suggestion1Regex = new Regex(@"Suggestion1\s*:\s*(.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
var suggestion2Regex = new Regex(@"Suggestion2\s*:\s*(.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
var suggestion3Regex = new Regex(@"Suggestion3\s*:\s*(.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
var reminderMatch = reminderRegex.Match(llmResponse);
if (reminderMatch.Success)
{
reminder = reminderMatch.Groups[1].Value.Trim();
}
else
{
Console.WriteLine("Could not find 'Reminder:' pattern in LLM response.");
}
var suggestion1Match = suggestion1Regex.Match(llmResponse);
if (suggestion1Match.Success)
{
suggestions.Add(suggestion1Match.Groups[1].Value.Trim());
}
else
{
Console.WriteLine("Could not find 'Suggestion1:' pattern in LLM response.");
}
var suggestion2Match = suggestion2Regex.Match(llmResponse);
if (suggestion2Match.Success)
{
suggestions.Add(suggestion2Match.Groups[1].Value.Trim());
}
else
{
Console.WriteLine("Could not find 'Suggestion2:' pattern in LLM response.");
}
var suggestion3Match = suggestion3Regex.Match(llmResponse);
if (suggestion3Match.Success)
{
string sug3 = suggestion3Match.Groups[1].Value.Trim();
if (!string.IsNullOrWhiteSpace(sug3) && !sug3.Equals("N/A", StringComparison.OrdinalIgnoreCase))
{
suggestions.Add(sug3);
}
}
// Optional: Log if Suggestion3 is not found, but it's optional so might be too noisy.
if (string.IsNullOrWhiteSpace(reminder) && !suggestions.Any())
{
Console.WriteLine($"Could not parse any reminder or suggestions from LLM response using regex: '{llmResponse}'.");
}
Console.WriteLine($"Parsed Reminder: \"{reminder}\", Suggestions: {suggestions.Count}");
return (reminder, suggestions);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing LLM reminder response with regex: {ex.Message}. Response was: {llmResponse}");
Console.WriteLine($"Defaulted Reminder/Suggestions due to exception: Reminder='', Suggestions=[]");
return (string.Empty, new List<string>());
}
}
public async Task<(string reminder, List<string> suggestions)> GenerateTaskReminderAsync(string taskDescription, TimeSpan timeSinceLastModified)
{
return await GenerateTaskReminderAsync(taskDescription, timeSinceLastModified, null);
}
public async Task<(string reminder, List<string> suggestions)> GenerateTaskReminderAsync(string taskDescription, TimeSpan timeSinceLastModified, string userContext)
{
if (string.IsNullOrWhiteSpace(taskDescription)) return (string.Empty, new List<string>());
string formattedAge = FormatTimeSpan(timeSinceLastModified);
string fullPrompt = TaskReminderSystemPrompt.Replace("{taskDescription}", taskDescription).Replace("{taskAge}", formattedAge);
if (!string.IsNullOrWhiteSpace(userContext))
{
fullPrompt += ReminderProfileHintTemplate.Replace("{userContext}", userContext);
}
string llmResponse = await GetCompletionAsync(fullPrompt);
if (IsErrorResponse(llmResponse))
{
Console.WriteLine($"LLM did not provide a valid reminder for '{taskDescription}'. Response: {llmResponse}");
throw new InvalidOperationException($"LLM API调用失败: {llmResponse}");
}
return ParseReminderResponse(llmResponse);
}
public async Task<List<LlmSkillRecommendation>> RecommendTaskSkillsAsync(
string taskDescription,
string importance,
string urgency,
TimeSpan inactiveDuration,
string userContext,
int maxSkills = 3)
{
if (string.IsNullOrWhiteSpace(taskDescription))
{
return new List<LlmSkillRecommendation>();
}
string context = string.IsNullOrWhiteSpace(userContext) ? "N/A" : userContext;
string prompt = SkillRecommendationSystemPromptTemplate
.Replace("{allowedSkillIds}", ThinkingToolAdvisor.GetAllowedSkillIdsCsv())
.Replace("{taskDescription}", taskDescription)
.Replace("{importance}", string.IsNullOrWhiteSpace(importance) ? "Unknown" : importance)
.Replace("{urgency}", string.IsNullOrWhiteSpace(urgency) ? "Unknown" : urgency)
.Replace("{inactiveDuration}", FormatTimeSpan(inactiveDuration))
.Replace("{userContext}", context);
try
{
string llmResponse = await GetCompletionAsync(prompt);
if (IsErrorResponse(llmResponse))
{
Console.WriteLine($"LLM skill recommendation failed for '{taskDescription}'. Fallback to rules. Response: {llmResponse}");
return GetRuleBasedSkillRecommendations(taskDescription, importance, urgency, inactiveDuration, maxSkills);
}
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var parsed = JsonSerializer.Deserialize<List<LlmSkillRecommendation>>(llmResponse, options) ?? new List<LlmSkillRecommendation>();
var filtered = parsed
.Where(s => s != null && IsAllowedSkillId(s.SkillId))
.Select(s => NormalizeSkillRecommendation(s))
.ToList();
var ruleBased = GetRuleBasedSkillRecommendations(taskDescription, importance, urgency, inactiveDuration, maxSkills);
var merged = filtered
.Concat(ruleBased)
.Where(s => s != null && IsAllowedSkillId(s.SkillId))
.GroupBy(s => s.SkillId, StringComparer.OrdinalIgnoreCase)
.Select(g => g.OrderByDescending(x => x.Confidence).First())
.OrderByDescending(s => s.Confidence)
.Take(Math.Max(1, maxSkills))
.ToList();
if (merged.Count > 0)
{
return merged;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing LLM skill recommendation, fallback to rules. {ex.Message}");
}
return GetRuleBasedSkillRecommendations(taskDescription, importance, urgency, inactiveDuration, maxSkills);
}
private static bool IsAllowedSkillId(string skillId)
{
return ThinkingToolAdvisor.IsAllowedSkillId(skillId);
}
private static LlmSkillRecommendation NormalizeSkillRecommendation(LlmSkillRecommendation s)
{
return new LlmSkillRecommendation
{
SkillId = (s.SkillId ?? "clarify_goal").Trim().ToLowerInvariant(),
Title = string.IsNullOrWhiteSpace(s.Title) ? "执行技能建议" : s.Title.Trim(),
Why = string.IsNullOrWhiteSpace(s.Why) ? "帮助你更快推进任务。" : s.Why.Trim(),
NextStep = string.IsNullOrWhiteSpace(s.NextStep) ? "先执行一个可在10分钟内完成的动作。" : s.NextStep.Trim(),
Confidence = Math.Max(0, Math.Min(1, s.Confidence))
};
}
private static List<LlmSkillRecommendation> GetRuleBasedSkillRecommendations(
string taskDescription,
string importance,
string urgency,
TimeSpan inactiveDuration,
int maxSkills)
{
var result = ThinkingToolAdvisor.RecommendForTask(taskDescription, importance, urgency, inactiveDuration, maxSkills + 2);
return result
.Select(r => new LlmSkillRecommendation
{
SkillId = (r.SkillId ?? "clarify_goal").Trim().ToLowerInvariant(),
Title = string.IsNullOrWhiteSpace(r.Title) ? "执行技能建议" : r.Title.Trim(),
Why = string.IsNullOrWhiteSpace(r.Why) ? "帮助你更快推进任务。" : r.Why.Trim(),
NextStep = string.IsNullOrWhiteSpace(r.NextStep) ? "先执行一个可在10分钟内完成的动作。" : r.NextStep.Trim(),
Confidence = Math.Max(0, Math.Min(1, r.Confidence))
})
.Where(s => IsAllowedSkillId(s.SkillId))
.GroupBy(s => s.SkillId, StringComparer.OrdinalIgnoreCase)
.Select(g => g.OrderByDescending(x => x.Confidence).First())
.OrderByDescending(s => s.Confidence)
.Take(Math.Max(1, maxSkills))
.ToList();
}
internal static (DecompositionStatus status, List<string> subtasks) ParseDecompositionResponse(string llmResponse)
{
Console.WriteLine($"Parsing LLM decomposition response: \"{llmResponse}\"");
var subtasks = new List<string>();
DecompositionStatus status = DecompositionStatus.Unknown;
if (string.IsNullOrWhiteSpace(llmResponse))
{
Console.WriteLine("LLM response is null or whitespace. Defaulting to Unknown status and empty subtasks.");
return (status, subtasks);
}
try
{
var statusRegex = new Regex(@"Status\s*:\s*(Sufficient|NeedsDecomposition)", RegexOptions.IgnoreCase);
var statusMatch = statusRegex.Match(llmResponse);
if (statusMatch.Success)
{
string statusStr = statusMatch.Groups[1].Value;
if (!Enum.TryParse(statusStr, true, out status))
{
status = DecompositionStatus.Unknown;
Console.WriteLine($"Could not parse decomposition status value '{statusStr}' from LLM response. Defaulting to Unknown.");
}
}
else
{
Console.WriteLine($"Could not find 'Status:' for decomposition in LLM response. Defaulting to Unknown.");
// No early return, will log final status and subtasks at the end
}
if (status == DecompositionStatus.NeedsDecomposition)
{
var subtasksRegex = new Regex(@"Subtasks\s*:\s*((?:.|\n)*)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
var subtasksMatch = subtasksRegex.Match(llmResponse);
if (subtasksMatch.Success)
{
string subtasksBlock = subtasksMatch.Groups[1].Value.Trim();
if (!string.IsNullOrWhiteSpace(subtasksBlock) && !subtasksBlock.Equals("N/A", StringComparison.OrdinalIgnoreCase))
{
string[] lines = subtasksBlock.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
string trimmedLine = line.Trim();
if (trimmedLine.StartsWith("-") || trimmedLine.StartsWith("*"))
{
trimmedLine = trimmedLine.Substring(1).Trim();
}
if (!string.IsNullOrWhiteSpace(trimmedLine) && !trimmedLine.Equals("N/A", StringComparison.OrdinalIgnoreCase))
{
subtasks.Add(trimmedLine);
}
}
}
if (!subtasks.Any())
{
Console.WriteLine($"Decomposition status is NeedsDecomposition but no valid subtasks found or parsed from block: '{subtasksBlock}'.");
}
}
else
{
Console.WriteLine($"Decomposition status is NeedsDecomposition but 'Subtasks:' block not found in LLM response.");
// Status might remain NeedsDecomposition but subtasks list will be empty.
}
}
Console.WriteLine($"Parsed Decomposition: Status={status}, Subtasks Count={subtasks.Count}");
return (status, subtasks);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing LLM decomposition response with regex: {ex.Message}. Response was: {llmResponse}");
Console.WriteLine($"Defaulted Decomposition due to exception: Status=Unknown, Subtasks=[]");
return (DecompositionStatus.Unknown, new List<string>());
}
}
public async Task<(DecompositionStatus status, List<string> subtasks)> DecomposeTaskAsync(string taskDescription)
{
if (string.IsNullOrWhiteSpace(taskDescription)) return (DecompositionStatus.Unknown, new List<string>());
string fullPrompt = TaskDecompositionSystemPrompt + taskDescription;
string llmResponse = await GetCompletionAsync(fullPrompt);
if (IsErrorResponse(llmResponse))
{
Console.WriteLine($"LLM did not provide a valid decomposition for '{taskDescription}'. Response: {llmResponse}");
return (DecompositionStatus.Unknown, new List<string>());
}
return ParseDecompositionResponse(llmResponse);
}
internal static (ClarityStatus status, string question) ParseClarityResponse(string llmResponse)
{
Console.WriteLine($"Parsing LLM clarity response: \"{llmResponse}\"");
ClarityStatus status = ClarityStatus.Unknown;
string question = string.Empty; // Default to empty string
if (string.IsNullOrWhiteSpace(llmResponse))
{
Console.WriteLine("LLM response is null or whitespace. Defaulting to Unknown status and empty question.");
question = "LLM response was empty."; // Keep original error message for this specific case
return (status, question);
}
try
{
var statusRegex = new Regex(@"Status\s*:\s*(Clear|NeedsClarification)", RegexOptions.IgnoreCase);
var questionRegex = new Regex(@"Question\s*:\s*((?:.|\n)*)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
var statusMatch = statusRegex.Match(llmResponse);
if (statusMatch.Success)
{
string statusStr = statusMatch.Groups[1].Value;
if (Enum.TryParse(statusStr, true, out ClarityStatus parsedStatus))
{
status = parsedStatus;
}
else
{
Console.WriteLine($"Could not parse clarity status value '{statusStr}' from LLM response. Defaulting to Unknown.");
status = ClarityStatus.Unknown;
}
}
else
{
Console.WriteLine("Could not find 'Status:' pattern in LLM response. Defaulting to Unknown status.");
// No early return, will log final status and question at the end
}
var questionMatch = questionRegex.Match(llmResponse);
if (questionMatch.Success)
{
question = questionMatch.Groups[1].Value.Trim();
if (status == ClarityStatus.Clear && (string.IsNullOrWhiteSpace(question) || question.Equals("N/A", StringComparison.OrdinalIgnoreCase)))
{
question = string.Empty; // Clear question if status is Clear and question is N/A or empty
}
}
else
{
Console.WriteLine("Could not find 'Question:' pattern in LLM response.");
if (status == ClarityStatus.NeedsClarification)
{
question = "Question expected but not found in response."; // More specific if status indicated a question was expected
} else if (status == ClarityStatus.Unknown) {
question = "Failed to parse status and question from LLM response.";
}
}
if (status == ClarityStatus.Unknown && !statusMatch.Success) { // If status is still unknown because regex failed
question = "Failed to parse status from LLM response.";
} else if (status == ClarityStatus.NeedsClarification && string.IsNullOrWhiteSpace(question)) {
Console.WriteLine("Warning: Status is NeedsClarification, but question is empty or N/A.");
// question = "Clarification needed, but no specific question was parsed."; // Optionally override if needed
}
Console.WriteLine($"Parsed Clarity: Status={status}, Question=\"{question}\"");
return (status, question);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing LLM clarity response with regex: {ex.Message}. Response was: {llmResponse}");
Console.WriteLine($"Defaulted Clarity due to exception: Status=Unknown, Question='Failed to analyze task clarity due to an exception.'");
return (ClarityStatus.Unknown, "Failed to analyze task clarity due to an exception.");
}
}
public async Task<(string importance, string urgency)> AnalyzeTaskPriorityAsync(string taskDescription)
{
if (string.IsNullOrWhiteSpace(taskDescription)) return ("Medium", "Medium");
string fullPrompt = PrioritizationSystemPrompt + taskDescription;
string llmResponse = await GetCompletionAsync(fullPrompt);
if (IsErrorResponse(llmResponse))
{
Console.WriteLine($"LLM did not provide a valid priority analysis for '{taskDescription}'. Response: {llmResponse}");
return ("Medium", "Medium");
}
return ParsePriorityResponse(llmResponse);
}
public async Task<(ClarityStatus status, string question)> AnalyzeTaskClarityAsync(string taskDescription)
{
if (string.IsNullOrWhiteSpace(taskDescription)) return (ClarityStatus.Unknown, "Task description cannot be empty.");
string fullPrompt = ClarityAnalysisSystemPrompt + taskDescription;
string llmResponse = await GetCompletionAsync(fullPrompt);
if (IsErrorResponse(llmResponse))
{
Console.WriteLine($"LLM did not provide a valid clarity analysis for '{taskDescription}'. Response: {llmResponse}");
return (ClarityStatus.Unknown, "Failed to analyze task clarity (LLM error or dummy response).");
}
return ParseClarityResponse(llmResponse);
}
internal static (string Importance, string Urgency) ParsePriorityResponse(string llmResponse)
{
Console.WriteLine($"Parsing LLM priority response: \"{llmResponse}\"");
if (string.IsNullOrWhiteSpace(llmResponse))
{
Console.WriteLine("LLM response is null or whitespace. Defaulting to Unknown/Unknown.");
return ("Unknown", "Unknown");
}
string importance = "Unknown";
string urgency = "Unknown";
try
{
// Regex to find "Importance: [value]" and "Urgency: [value]", case-insensitive labels, flexible whitespace
var importanceRegex = new Regex(@"Importance\s*:\s*([A-Za-z]+)", RegexOptions.IgnoreCase);
var urgencyRegex = new Regex(@"Urgency\s*:\s*([A-Za-z]+)", RegexOptions.IgnoreCase);
var importanceMatch = importanceRegex.Match(llmResponse);
var urgencyMatch = urgencyRegex.Match(llmResponse);
string[] validPriorities = { "High", "Medium", "Low" };
var validPrioritySet = new HashSet<string>(validPriorities, StringComparer.OrdinalIgnoreCase);
if (importanceMatch.Success)
{
string extractedImportance = importanceMatch.Groups[1].Value.Trim();
if (validPrioritySet.Contains(extractedImportance))
{
// Normalize to title case e.g. "high" -> "High"
importance = validPriorities.First(p => p.Equals(extractedImportance, StringComparison.OrdinalIgnoreCase));
}
else
{
Console.WriteLine($"Extracted importance '{extractedImportance}' is not a valid priority. Defaulting to Unknown.");
}
}
else
{
Console.WriteLine("Could not find 'Importance:' pattern in LLM response.");
}
if (urgencyMatch.Success)
{
string extractedUrgency = urgencyMatch.Groups[1].Value.Trim();
if (validPrioritySet.Contains(extractedUrgency))
{
// Normalize to title case
urgency = validPriorities.First(p => p.Equals(extractedUrgency, StringComparison.OrdinalIgnoreCase));
}
else
{
Console.WriteLine($"Extracted urgency '{extractedUrgency}' is not a valid priority. Defaulting to Unknown.");
}
}
else
{
Console.WriteLine("Could not find 'Urgency:' pattern in LLM response.");
}
if (importance == "Unknown" && urgency == "Unknown" && !importanceMatch.Success && !urgencyMatch.Success)
{
Console.WriteLine($"Could not parse Importance or Urgency from LLM response using regex: '{llmResponse}'. Both remain Unknown.");
}
Console.WriteLine($"Parsed Priority: Importance={importance}, Urgency={urgency}");
return (importance, urgency);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing LLM priority response with regex: {ex.Message}. Response was: {llmResponse}");
Console.WriteLine($"Defaulted Priority due to exception: Importance=Unknown, Urgency=Unknown");
return ("Unknown", "Unknown");
}
}
public async Task<(string Importance, string Urgency)> GetTaskPriorityAsync(string taskDescription)
{
if (string.IsNullOrWhiteSpace(taskDescription)) return ("Unknown", "Unknown");
string fullPrompt = PrioritizationSystemPrompt + taskDescription;
string llmResponse = await GetCompletionAsync(fullPrompt);
if (IsErrorResponse(llmResponse))
{
Console.WriteLine($"LLM did not provide a valid priority response for '{taskDescription}'. Response: {llmResponse}");
return ("Unknown", "Unknown");
}
return ParsePriorityResponse(llmResponse);
}
public async Task<List<string>> ExtractTasksFromConversationAsync(string conversation)
{
if (string.IsNullOrWhiteSpace(conversation))
return new List<string>();
string prompt = ConversationTaskExtractPrompt + conversation;
string llmResponse = await GetCompletionAsync(prompt);
if (IsErrorResponse(llmResponse))
{
Console.WriteLine($"LLM did not provide valid conversation extraction. Response: {llmResponse}");
return new List<string>();
}
try
{
var tasks = JsonSerializer.Deserialize<List<string>>(llmResponse);
if (tasks != null && tasks.Count > 0)
return tasks.Where(t => !string.IsNullOrWhiteSpace(t)).ToList();
}
catch { }
// Fallback parse: split lines
var lines = llmResponse.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Select(l => l.Trim().TrimStart('-', '*', '•'))
.Where(l => !string.IsNullOrWhiteSpace(l))
.ToList();
return lines;
}
private void LoadLlmConfig() // Renamed and updated
{
try
{
_apiKey = ConfigurationManager.AppSettings["OpenAIApiKey"];
_apiBaseUrl = ConfigurationManager.AppSettings["LlmApiBaseUrl"]; // Load new setting
_modelName = ConfigurationManager.AppSettings["LlmModelName"]; // Load new setting
string timeoutSetting = ConfigurationManager.AppSettings["LlmRequestTimeoutSeconds"];
if (!string.IsNullOrWhiteSpace(timeoutSetting) && int.TryParse(timeoutSetting, out int timeoutSeconds) && timeoutSeconds > 0)
{
_httpClientTimeout = TimeSpan.FromSeconds(timeoutSeconds);
Console.WriteLine($"LLM Service: Using configured HTTP client timeout of {timeoutSeconds} seconds.");
}
else
{
Console.WriteLine($"LLM Service: LlmRequestTimeoutSeconds setting is missing, invalid, or not positive. Using default timeout of {_httpClientTimeout.TotalSeconds} seconds.");
}
}
catch (ConfigurationErrorsException ex)