-
Notifications
You must be signed in to change notification settings - Fork 26
/
GptCaller.cs
99 lines (89 loc) · 2.92 KB
/
GptCaller.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using OpenAI_API;
using OpenAI_API.Chat;
using System.Net;
namespace ja_learner
{
internal class GptCaller
{
private static OpenAIAPI api;
private static IHttpClientFactory defaultFactory;
private static IHttpClientFactory proxyFactory;
public static void Initialize()
{
api = new(Program.APP_SETTING.GPT.ApiKey) { ApiUrlFormat = Program.APP_SETTING.GPT.ApiUrl };
defaultFactory = api.HttpClientFactory;
proxyFactory = new MyHttpClientFactory(Program.APP_SETTING.HttpProxy);
}
public static void SetProxy(bool useProxy)
{
if (useProxy)
{
api.HttpClientFactory = proxyFactory;
}
else
{
api.HttpClientFactory = defaultFactory;
}
}
public static Conversation CreateTranslateConversation(string text)
{
Conversation conversation = api.Chat.CreateConversation();
conversation.AppendSystemMessage(Program.APP_SETTING.GPT.TranslatePrompt);
if (UserConfig.useExtraPrompt)
{
AddExtraSystemPrompt(conversation);
}
conversation.AppendUserInput($"{text}");
return conversation;
}
public static Conversation CreateInterpretConversation(string text)
{
Conversation conversation = api.Chat.CreateConversation();
conversation.AppendSystemMessage(Program.APP_SETTING.GPT.ExplainPrompt);
if (UserConfig.useExtraPrompt)
{
AddExtraSystemPrompt(conversation);
}
conversation.AppendUserInput($"{text}");
return conversation;
}
private static void AddExtraSystemPrompt(Conversation conversation)
{
if (UserConfig.ExtraPrompt.Length > 0)
{
conversation.AppendSystemMessage(UserConfig.ExtraPrompt);
}
}
async public static void StreamResponse(Conversation conversation, Action<string> callback)
{
try
{
await foreach (var res in conversation.StreamResponseEnumerableFromChatbotAsync())
{
callback(res);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
class MyHttpClientFactory : IHttpClientFactory
{
private string proxy;
public MyHttpClientFactory(string proxy)
{
this.proxy = proxy;
}
HttpClient IHttpClientFactory.CreateClient(string name)
{
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy($"http://{proxy}")
};
var client = new HttpClient(handler);
return client;
}
}
}