-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
86 lines (79 loc) · 2.76 KB
/
Program.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
using System.Text;
using System.Text.Json;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
AppSetting? appSetting=null;
try
{
appSetting =JsonSerializer.Deserialize<AppSetting>(File.ReadAllText("appsetting.json"));
}
catch
{
}
if (appSetting==null)
{
appSetting=new AppSetting();
Console.WriteLine("请填写必要信息");
Console.WriteLine("请输入ApiUrl(需要兼容OpenAI的接口):");
appSetting.ApiUrl=Console.ReadLine()?.Trim();
Console.WriteLine("请输入ModelId:");
appSetting.ModelId=Console.ReadLine()?.Trim();
Console.WriteLine("请输入ApiKey(如果是本地部署则可能没有,可以直接回车不填):");
appSetting.ApiKey=Console.ReadLine()?.Trim();
}
if (string.IsNullOrEmpty(appSetting.ApiKey)) appSetting.ApiKey="xxxxxxx";//不填会报错,所以没有就填一个无效的
string modelId= appSetting.ModelId?.Trim();
string apiKey = appSetting.ApiKey?.Trim();
string uri = appSetting.ApiUrl?.Trim();
var builder = Kernel.CreateBuilder();
var kernel = builder.AddOpenAIChatCompletion(
modelId: modelId,
apiKey: apiKey,
httpClient: new HttpClient(new OpenAIHttpClientHandler(uri)))
.Build();
ChatHistory chatHistory = new ChatHistory();
var agent = CreateDefaultAgent(kernel);
string? readText;
Console.Write("提问:");
while (!string.IsNullOrEmpty(readText=Console.ReadLine()))
{
chatHistory.AddUserMessage(readText);
StringBuilder sb = new StringBuilder();
Console.Write("回答:");
await foreach(var item in agent.InvokeStreamingAsync(chatHistory))
{
var text = item.Content;
sb.Append(text);
Console.Write(text);
}
chatHistory.AddAssistantMessage(sb.ToString());
Console.WriteLine();
Console.Write("提问:");
}
ChatCompletionAgent CreateDefaultAgent(Kernel kernel)
{
string promptTemplate = File.ReadAllText("PromptTemplate.txt");
var newKernel = kernel.Clone();
newKernel.Plugins.AddRange([
KernelPluginFactory.CreateFromFunctions("datetime_plugin", [
KernelFunctionFactory.CreateFromMethod(() =>
{
return DateTime.Now.ToString();
},"get_datetime_now","获取当前系统日期时间")
]),
KernelPluginFactory.CreateFromType<CMDPlugin>("cmd_plugin")
]
);
return new ChatCompletionAgent()
{
Name = "电脑管家",
Instructions = promptTemplate,
Kernel = newKernel,
Arguments = new KernelArguments(new OpenAIPromptExecutionSettings()
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
})
};
}