-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
421 lines (373 loc) · 14.8 KB
/
Copy pathProgram.cs
File metadata and controls
421 lines (373 loc) · 14.8 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
using AIAgentTaskPlanner;
using AIAgentTaskPlanner.Examples;
using AIAgentTaskPlanner.Models;
using AIAgentTaskPlanner.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
// 构建配置
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddUserSecrets<Program>() // 添加用户机密支持
.Build();
// 配置 AI 服务
Console.WriteLine("🔧 配置 AI 服务...");
Kernel kernel;
// 从 appsettings.json 读取配置
var openAiApiKey = configuration["OpenAI:ApiKey"];
var openAiModel = configuration["OpenAI:Model"] ?? "gpt-4.1";
var azureOpenAiApiKey = configuration["AzureOpenAI:ApiKey"];
var azureOpenAiEndpoint = configuration["AzureOpenAI:Endpoint"];
var azureOpenAiDeployment = configuration["AzureOpenAI:DeploymentName"] ?? "gpt-4.1";
if (!string.IsNullOrWhiteSpace(openAiApiKey) && openAiApiKey != "your-openai-api-key-here")
{
Console.WriteLine("✅ 使用 OpenAI 服务");
kernel = KernelConfiguration.CreateWithOpenAI(openAiApiKey, openAiModel);
}
else if (!string.IsNullOrWhiteSpace(azureOpenAiApiKey) && !string.IsNullOrWhiteSpace(azureOpenAiEndpoint))
{
Console.WriteLine("✅ 使用 Azure OpenAI 服务");
kernel = KernelConfiguration.CreateWithAzureOpenAI(azureOpenAiDeployment, azureOpenAiEndpoint, azureOpenAiApiKey);
// 测试 Azure OpenAI 连接
await TestAIServiceConnection(kernel, "Azure OpenAI");
}
else
{
Console.WriteLine("⚠️ 未检测到 AI 服务配置,使用演示模式");
Console.WriteLine(" 要使用真实 AI 服务,请修改 appsettings.json 中的配置:");
Console.WriteLine(" - OpenAI:ApiKey (对于 OpenAI)");
Console.WriteLine(" - AzureOpenAI:ApiKey 和 AzureOpenAI:Endpoint (对于 Azure OpenAI)");
kernel = KernelConfiguration.CreateDemo();
}
// 配置服务容器
var serviceProvider = KernelConfiguration.ConfigureServices(kernel);
var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
var taskPlanningService = serviceProvider.GetRequiredService<TaskPlanningService>();
Console.WriteLine("🤖 AI Agent 任务规划系统");
Console.WriteLine("基于 .NET 9 + Semantic Kernel");
Console.WriteLine("=====================================\n");
// 主程序循环
while (true)
{
try
{
Console.WriteLine("请选择操作:");
Console.WriteLine("1. 创建任务计划");
Console.WriteLine("2. 搜索知识库");
Console.WriteLine("3. 提交反馈");
Console.WriteLine("4. 查看知识库统计");
Console.WriteLine("5. 测试流式输出");
Console.WriteLine("9. 测试重构功能");
Console.WriteLine("0. 退出");
Console.Write("\n请输入选项 (0-9): ");
var choice = Console.ReadLine()?.Trim();
// 如果输入为null(如管道输入结束),默认退出
if (choice == null)
{
Console.WriteLine("\n检测到输入结束,程序退出。再见!👋");
return;
}
switch (choice)
{
case "1":
await CreateTaskPlan(taskPlanningService);
break;
case "2":
await SearchKnowledge(taskPlanningService);
break;
case "3":
await SubmitFeedback(taskPlanningService);
break;
case "4":
await ExampleUtils.ShowKnowledgeStats(taskPlanningService);
break;
case "0":
Console.WriteLine("再见!👋");
return;
default:
Console.WriteLine("无效选项,请重试。\n");
break;
}
}
catch (Exception ex)
{
logger.LogError(ex, "程序执行出错");
Console.WriteLine($"❌ 发生错误: {ex.Message}\n");
}
}
// 创建任务计划
static async Task CreateTaskPlan(TaskPlanningService service)
{
Console.WriteLine("\n📝 创建任务计划");
Console.WriteLine("请输入你的需求描述:");
var input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("\n❌ 无法分析结果:输入不能为空");
Console.WriteLine();
return;
}
Console.WriteLine("⏳ 正在分析并生成任务计划...");
try
{
SystemOutput? result = null;
#region 流式处理
//var lastMessage = "";
// 使用流式处理显示实时进度
//await foreach (var update in service.ProcessUserInputStreamAsync(input))
//{
// // 如果消息改变了,显示新消息
// if (update.AIPartialContent != lastMessage)
// {
// if (!string.IsNullOrEmpty(lastMessage))
// {
// Console.WriteLine(); // 完成上一个消息
// }
// Console.Write($"🔄 {update.AIPartialContent}");
// lastMessage = update.AIPartialContent;
// }
// // 如果任务完成,从Data中提取结果
// if (update.IsComplete && update.Data is SystemOutput systemOutput)
// {
// result = systemOutput;
// Console.WriteLine(" ✅");
// break;
// }
// // 显示进度动画
// Console.Write(".");
// await Task.Delay(50);
//}
#endregion
// 如果流式处理没有返回最终结果,使用后备方案
if (result == null)
{
Console.WriteLine("\n🔄 完成处理,正在整理结果...");
result = await service.ProcessUserInputAsync(input);
}
// 检查结果是否有效
if (result == null)
{
Console.WriteLine("\n❌ 无法分析结果:系统未能生成有效的任务计划");
Console.WriteLine("可能原因:");
Console.WriteLine("- 输入内容无法被理解或识别");
Console.WriteLine("- AI服务暂时不可用");
Console.WriteLine("- 输入格式不正确");
Console.WriteLine("\n建议:请尝试重新描述您的需求,使用更清晰的表达方式");
}
else if (string.IsNullOrWhiteSpace(result.TaskAnalysis) &&
string.IsNullOrWhiteSpace(result.RagOperations) &&
(result.TodoList == null || string.IsNullOrWhiteSpace(result.TodoList.Title)))
{
Console.WriteLine("\n❌ 无法分析结果:生成的任务计划为空");
Console.WriteLine("可能原因:");
Console.WriteLine("- 输入内容过于简单或模糊");
Console.WriteLine("- 缺少必要的任务描述信息");
Console.WriteLine("- 系统无法识别具体的操作需求");
Console.WriteLine("\n建议:请提供更详细的任务描述和具体要求");
}
else
{
Console.WriteLine("\n✅ 任务计划生成完成!\n");
// 显示结果
try
{
var markdown = await service.ExportToMarkdownAsync(result);
if (string.IsNullOrWhiteSpace(markdown))
{
Console.WriteLine("❌ 无法分析结果:任务计划格式化失败");
Console.WriteLine("系统生成了任务计划,但无法将其转换为可读格式");
Console.WriteLine("\n建议:请重试或联系技术支持");
}
else
{
Console.WriteLine(markdown);
// 询问是否保存
Console.Write("\n是否要保存为文件?(y/n): ");
if (Console.ReadLine()?.ToLower() == "y")
{
var fileName = $"TaskPlan_{DateTime.Now:yyyyMMdd_HHmmss}.md";
await File.WriteAllTextAsync(fileName, markdown);
Console.WriteLine($"✅ 已保存为: {fileName}");
}
}
}
catch (Exception markdownEx)
{
Console.WriteLine("❌ 无法分析结果:格式化输出时发生错误");
Console.WriteLine($"错误详情: {markdownEx.Message}");
Console.WriteLine("\n任务计划已生成,但无法正确显示");
Console.WriteLine("建议:请重试或检查系统配置");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"\n❌ 无法分析结果:生成任务计划时发生错误");
Console.WriteLine($"错误详情: {ex.Message}");
Console.WriteLine("\n可能原因:");
Console.WriteLine("- AI服务连接问题");
Console.WriteLine("- 输入内容包含无法处理的特殊字符");
Console.WriteLine("- 系统资源不足");
Console.WriteLine("\n建议:请检查网络连接并重试,或使用英文描述您的需求");
}
Console.WriteLine("\n按任意键继续...");
Console.ReadKey();
Console.WriteLine();
}
// 搜索知识库
static async Task SearchKnowledge(TaskPlanningService service)
{
Console.WriteLine("\n🔍 搜索知识库");
Console.Write("请输入搜索关键词: ");
var query = Console.ReadLine();
if (string.IsNullOrWhiteSpace(query))
{
Console.WriteLine("搜索关键词不能为空。\n");
return;
}
try
{
var results = await service.SearchKnowledgeAsync(query);
if (!results.Any())
{
Console.WriteLine("未找到相关结果。");
}
else
{
Console.WriteLine($"\n找到 {results.Count} 个相关结果:\n");
for (int i = 0; i < results.Count; i++)
{
var entry = results[i];
Console.WriteLine($"📄 结果 {i + 1}");
Console.WriteLine($"ID: {entry.Id}");
Console.WriteLine($"分类: {entry.Classification.Category}");
Console.WriteLine($"标签: {string.Join(", ", entry.Classification.Tags)}");
Console.WriteLine($"内容预览: {entry.Content[..Math.Min(100, entry.Content.Length)]}...");
Console.WriteLine($"用户反馈: {entry.UserFeedback?.ToString() ?? "未评价"}");
Console.WriteLine($"更新时间: {entry.LastUpdated:yyyy-MM-dd HH:mm:ss}");
Console.WriteLine();
}
}
}
catch (Exception ex)
{
Console.WriteLine($"❌ 搜索时出错: {ex.Message}");
}
Console.WriteLine("按任意键继续...");
Console.ReadKey();
Console.WriteLine();
}
// 提交反馈
static async Task SubmitFeedback(TaskPlanningService service)
{
Console.WriteLine("\n💬 提交用户反馈");
Console.Write("请输入知识条目ID: ");
var entryId = Console.ReadLine();
if (string.IsNullOrWhiteSpace(entryId))
{
Console.WriteLine("条目ID不能为空。\n");
return;
}
Console.Write("分类是否准确?(y/n): ");
var isAccurate = Console.ReadLine()?.ToLower() == "y";
Console.Write("请输入评论(可选): ");
var comments = Console.ReadLine() ?? "";
var feedback = new UserFeedback
{
EntryId = entryId,
IsAccurate = isAccurate,
Comments = comments
};
try
{
var result = await service.ProcessUserFeedbackAsync(feedback);
Console.WriteLine($"✅ {result}");
}
catch (Exception ex)
{
Console.WriteLine($"❌ 提交反馈时出错: {ex.Message}");
}
Console.WriteLine("\n按任意键继续...");
Console.ReadKey();
Console.WriteLine();
}
// 测试 AI 服务连接的辅助方法
static async Task TestAIServiceConnection(Kernel kernel, string serviceName)
{
try
{
Console.Write("🔍 正在测试 AI 服务连接...");
// 获取聊天完成服务
var chatService = kernel.GetRequiredService<IChatCompletionService>();
// 创建一个简单的测试消息
var chatHistory = new ChatHistory();
chatHistory.AddUserMessage("你好,请回复'连接成功',并告诉我你是用的模型。来确认服务正常");
// 设置超时时间为10秒
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
// 发送测试请求
var response = await chatService.GetChatMessageContentAsync(
chatHistory,
new OpenAIPromptExecutionSettings
{
MaxTokens = 50,
Temperature = 0.1
},
cancellationToken: cts.Token);
if (!string.IsNullOrWhiteSpace(response?.Content))
{
Console.WriteLine(" ✅ 连接成功!");
Console.WriteLine($" 📡 服务: {serviceName}");
Console.WriteLine($" 💬 测试响应: {response.Content[..Math.Min(50, response.Content.Length)]}...");
}
else
{
Console.WriteLine(" ⚠️ 连接成功但响应为空");
}
}
catch (HttpRequestException ex)
{
Console.WriteLine(" ❌ 网络连接失败");
Console.WriteLine($" 错误: {ex.Message}");
Console.WriteLine(" 💡 请检查网络连接和服务端点配置");
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine(" ❌ 认证失败");
Console.WriteLine($" 错误: {ex.Message}");
Console.WriteLine(" 💡 请检查 API 密钥是否正确");
}
catch (TaskCanceledException)
{
Console.WriteLine(" ❌ 连接超时");
Console.WriteLine(" 💡 请检查网络连接或尝试稍后重试");
}
catch (Exception ex)
{
Console.WriteLine(" ❌ 连接失败");
Console.WriteLine($" 错误类型: {ex.GetType().Name}");
Console.WriteLine($" 错误信息: {ex.Message}");
// 提供具体的故障排除建议
if (ex.Message.Contains("401"))
{
Console.WriteLine(" 💡 建议: API 密钥可能无效,请检查 appsettings.json 中的配置");
}
else if (ex.Message.Contains("404"))
{
Console.WriteLine(" 💡 建议: 部署名称或端点可能不正确");
}
else if (ex.Message.Contains("429"))
{
Console.WriteLine(" 💡 建议: 请求频率过高,请稍后重试");
}
else if (ex.Message.Contains("timeout"))
{
Console.WriteLine(" 💡 建议: 网络连接超时,请检查网络连接");
}
}
Console.WriteLine(); // 添加一个空行
}