forked from TimShaw1/Wendigos-Mod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChatManager.cs
76 lines (70 loc) · 2.4 KB
/
ChatManager.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
using Newtonsoft.Json;
using OpenAI;
using OpenAI.Chat;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Wendigos
{
public static class ChatManager
{
static HttpClient client;
public static bool init_success = false;
private static string gpt_model;
public static void Init(string api_key, string modelToUse)
{
try
{
if (api_key.Length == 0)
{
throw new ArgumentException("No ChatGPT API key!");
return;
}
client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer {api_key}");
gpt_model = modelToUse;
Console.WriteLine("CHATGPT INIT SUCCESS");
init_success = true;
}
catch (Exception ex)
{
Console.WriteLine("CHATGPT INIT FAILED");
Console.WriteLine(ex.Message);
}
}
public static string SendPromptToChatGPT(string prompt)
{
try
{
var requestBody = new
{
model = gpt_model,
messages = new[]
{
new { role = "user", content = prompt }
},
max_tokens = 200
};
var content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
var task = client.PostAsync("https://api.openai.com/v1/chat/completions", content);
task.Wait();
var response = task.Result;
response.EnsureSuccessStatusCode();
var task2 = response.Content.ReadAsStringAsync();
task2.Wait();
var responseContent = task2.Result;
dynamic jsonResponse = JsonConvert.DeserializeObject(responseContent);
Console.WriteLine("MESSAGE RECIEVED");
return jsonResponse.choices[0].message.content;
}
catch (Exception ex)
{
Console.WriteLine("CHAT BROKE");
Console.WriteLine(ex.ToString());
return "";
}
}
}
}