-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
228 lines (183 loc) · 6.88 KB
/
Program.cs
File metadata and controls
228 lines (183 loc) · 6.88 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
using DotNetEnv;
using Valour.Sdk.Client;
using Valour.Sdk.Models;
using SkyAI;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
namespace SkyAI;
public class ChatMessage
{
public string role { get; set; } = "";
public string content { get; set; } = "";
}
public class Program
{
const int MaxHistoryMessages = 10;
const int MaxResponseLength = 2048;
const string ModelName = "llama3.1:latest";
const string prefix = "s.";
const string sourceLink = "https://github.com/SkyJoshua/SkyAI";
private static readonly Dictionary<long, Channel> channelCache = new();
private static readonly Dictionary<long, List<ChatMessage>> ChatHistory = new();
private static readonly HashSet<long> InitializedPlanets = new();
public static async Task Main()
{
Env.Load();
var token = Environment.GetEnvironmentVariable("TOKEN");
var openWebApi = Environment.GetEnvironmentVariable("OPENWEBAPI");
var openWebUrl = Environment.GetEnvironmentVariable("OPENWEBURL");
if (string.IsNullOrWhiteSpace(token) ||
string.IsNullOrWhiteSpace(openWebApi) ||
string.IsNullOrWhiteSpace(openWebUrl))
{
Console.WriteLine("Missing required environment variables.");
return;
}
var client = new ValourClient("https://api.valour.gg/");
client.SetupHttpClient();
var loginResult = await client.InitializeUser(token);
if (!loginResult.Success)
{
Console.WriteLine($"Login Failed: {loginResult.Message}");
return;
}
Console.WriteLine($"Logged in as {client.Me.Name}");
await Utils.InitializePlanetsAsync(client, channelCache, InitializedPlanets);
var httpClient = new HttpClient
{
BaseAddress = new Uri(openWebUrl)
};
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", openWebApi);
client.MessageService.MessageReceived += async (message) =>
{
if (string.IsNullOrWhiteSpace(message.Content))
return;
var content = message.Content;
var channelId = message.ChannelId;
var member = await message.FetchAuthorMemberAsync();
var ping = $"«@m-{member.Id}»";
if (content.StartsWith($"{prefix}cm"))
{
ChatHistory.Remove(channelId);
await Utils.SendReplyAsync(channelCache, channelId, $"{ping} Channel memory cleared.");
return;
}
if (content.StartsWith($"{prefix}source"))
{
await Utils.SendReplyAsync(channelCache, channelId, $"{ping} You can find my source code here: {sourceLink}");
}
if (!content.StartsWith($"{prefix}ai"))
return;
var prompt = content.Substring(prefix.Length+3).Trim();
if (string.IsNullOrWhiteSpace(prompt))
{
await Utils.SendReplyAsync(channelCache, channelId, $"{ping} Enter a question.");
return;
}
var history = GetOrCreateHistory(channelId);
history.Add(new ChatMessage { role = "user", content = $"User: {member.Name} (ID: {member.Id}) | {prompt}" });
TrimHistory(history);
var payload = new
{
model = ModelName,
messages = history
};
var json = JsonSerializer.Serialize(payload);
HttpResponseMessage response;
try
{
response = await httpClient.PostAsync(
"/api/chat/completions",
new StringContent(json, Encoding.UTF8, "application/json")
);
}
catch (HttpRequestException ex)
{
await Utils.SendReplyAsync(
channelCache,
channelId,
$"{ping} Cannot reach OpenWebUI server. Check OPENWEBURL.\nError: {ex.Message}"
);
return;
}
catch (TaskCanceledException)
{
await Utils.SendReplyAsync(
channelCache,
channelId,
$"{ping} Connection timed out. Check OPENWEBURL."
);
return;
}
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
await Utils.SendReplyAsync(
channelCache,
channelId,
$"{ping} OpenWebUI API key is invalid."
);
return;
}
if (!response.IsSuccessStatusCode)
{
var errorBody = await response.Content.ReadAsStringAsync();
await Utils.SendReplyAsync(
channelCache,
channelId,
$"{ping} OpenWebUI error {(int)response.StatusCode}:\n{errorBody}"
);
return;
}
var responseText = await response.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(responseText);
var output = doc.RootElement
.GetProperty("choices")[0]
.GetProperty("message")
.GetProperty("content")
.GetString() ?? "";
history.Add(new ChatMessage { role = "assistant", content = output });
output = $"{ping} {output}";
output = Truncate(output);
await Utils.SendReplyAsync(channelCache, channelId, output);
};
Console.WriteLine("Listening...");
await Task.Delay(Timeout.Infinite);
}
private static List<ChatMessage> GetOrCreateHistory(long channelId)
{
if (!ChatHistory.ContainsKey(channelId))
{
ChatHistory[channelId] = new List<ChatMessage>
{
new ChatMessage
{
role = "system",
content = "You are a helpful AI assistant. Keep responses under 2048 characters."
}
};
}
return ChatHistory[channelId];
}
private static void TrimHistory(List<ChatMessage> history)
{
if (history.Count <= (MaxHistoryMessages * 2) + 1)
return;
var system = history[0];
var trimmed = history
.Skip(history.Count - (MaxHistoryMessages * 2))
.ToList();
trimmed.Insert(0, system);
history.Clear();
history.AddRange(trimmed);
}
private static string Truncate(string text)
{
if (string.IsNullOrEmpty(text))
return text;
return text.Length <= MaxResponseLength
? text
: text.Substring(0, MaxResponseLength);
}
}