-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.axaml.cs
More file actions
312 lines (250 loc) · 10.9 KB
/
MainWindow.axaml.cs
File metadata and controls
312 lines (250 loc) · 10.9 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
using Avalonia.Controls;
using Avalonia.Interactivity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Mark1
{
public partial class MainWindow : Window
{
public ObservableCollection<ChatMessage> ChatHistory { get; set; }
public TextBox? ResponseTextBox { get; }
public MainWindow()
{
InitializeComponent();
InputTextBox = this.FindControl<TextBox>("InputTextBox");
ResponseTextBox = this.FindControl<TextBox>("ResponseTextBox");
InputTextBoxApikey = this.FindControl<TextBox>("InputTextBoxApikey");
ProviderComboBox = this.FindControl<ComboBox>("ProviderComboBox");
ChatHistory = new ObservableCollection<ChatMessage>();
DataContext = this;
// Load configuration on startup
Configuration config = LoadConfiguration();
if (config != null)
{
// Assign API key to TextBox
InputTextBoxApikey.Text = config.ApiKey;
// Select provider in ComboBox
var item = ProviderComboBox.Items
.OfType<ComboBoxItem>()
.FirstOrDefault(i => i.Content.ToString() == config.SelectedProvider);
if (item != null)
{
ProviderComboBox.SelectedItem = item;
}
}
}
private void ConfigurationProvider(object sender, RoutedEventArgs e)
{
string apiKey = InputTextBoxApikey.Text ?? string.Empty;
string? selectedProvider = (ProviderComboBox.SelectedItem as ComboBoxItem)?.Content?.ToString();
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Por favor, ingresa una clave de API.");
return;
}
if (string.IsNullOrEmpty(selectedProvider))
{
Console.WriteLine("Por favor, selecciona un proveedor.");
return;
}
SaveConfiguration(apiKey, selectedProvider);
Console.WriteLine($"Proveedor: {selectedProvider}\nClave API configurada correctamente.");
}
private void SaveConfiguration(string apiKey, string selectedProvider)
{
Configuration config = new Configuration
{
ApiKey = apiKey,
SelectedProvider = selectedProvider
};
string json = JsonConvert.SerializeObject(config, Formatting.Indented);
string filePath = "config.json"; // Ruta del archivo JSON
System.IO.File.WriteAllText(filePath, json);
Console.WriteLine("Configuración guardada.");
}
private Configuration? LoadConfiguration()
{
string filePath = "config.json"; // Ruta del archivo JSON
if (System.IO.File.Exists(filePath))
{
string json = System.IO.File.ReadAllText(filePath);
if (string.IsNullOrWhiteSpace(json))
{
Console.WriteLine("El archivo de configuración está vacío.");
return null;
}
try
{
Configuration config = JsonConvert.DeserializeObject<Configuration>(json) ?? new Configuration();
Console.WriteLine($"Leyendo Configuración: {config.ApiKey} - {config.SelectedProvider}");
return config;
}
catch (JsonException ex)
{
Console.WriteLine("Error al leer la configuración: " + ex.Message);
return null;
}
}
else
{
Console.WriteLine("No se encontró el archivo de configuración.");
return null;
}
}
private async void OnSendButtonClick(object sender, RoutedEventArgs e)
{
string userInput = InputTextBox?.Text ?? string.Empty;
if (string.IsNullOrEmpty(userInput))
{
Console.WriteLine("Please enter a query.");
return;
}
string apiKey = InputTextBoxApikey.Text ?? string.Empty;
string? selectedProvider = (ProviderComboBox.SelectedItem as ComboBoxItem)?.Content?.ToString();
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API key is empty.");
return;
}
if (string.IsNullOrEmpty(selectedProvider))
{
Console.WriteLine("Please select a provider.");
return;
}
ChatHistory.Add(new ChatMessage
{
Message = $"You: {userInput}",
Timestamp = DateTime.Now.ToString("HH:mm:ss")
});
string response = await MakeRequestToProvider(selectedProvider, apiKey, userInput);
ChatHistory.Add(new ChatMessage
{
Message = $"Bot: {response}",
Timestamp = DateTime.Now.ToString("HH:mm:ss")
});
InputTextBox?.Clear();
}
private async Task<string> MakeRequestToProvider(string provider, string apiKey, string userInput)
{
switch (provider)
{
case "Open":
return await CallOpenIAFunction(apiKey, userInput);
case "Gemine":
return await CallGemineFunction(apiKey, userInput);
case "Huggy":
return await CallHuggyFaceFunction(apiKey, userInput);
default:
return "Invalid provider.";
}
}
private async Task<string> CallOpenIAFunction(string apiKey, string userInput)
{
string apiUrl = "https://api.openai.com/v1/completions";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
var requestData = new { prompt = userInput, max_tokens = 100 };
var jsonContent = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");
var response = await client.PostAsync(apiUrl, jsonContent);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
var jsonResponse = JsonConvert.DeserializeObject<dynamic>(responseBody);
return jsonResponse?.choices?[0]?.text?.ToString()?.Trim() ?? "No response.";
}
}
public async Task<string> CallGemineFunction(string apiKey, string prompt)
{
using (var client = new HttpClient())
{
try
{
string apiUrlGemine = $"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={apiKey}";
var requestData = new
{
contents = new[] {
new {
parts = new[] {
new { text = prompt }
}
}
}
};
var jsonContent = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");
var response = await client.PostAsync(apiUrlGemine, jsonContent);
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
var jsonResponse = JObject.Parse(responseBody);
var text = jsonResponse["candidates"]?[0]?["content"]?["parts"]?[0]?["text"]?.ToString();
return text ?? "No content found in response";
}
else
{
string errorMessage = $"Error: {response.StatusCode} - {response.ReasonPhrase}";
return errorMessage;
}
}
catch (HttpRequestException ex)
{
return $"HttpRequestException: {ex.Message}";
}
catch (Exception ex)
{
return $"Exception: {ex.Message}";
}
}
}
private async Task<string> CallHuggyFaceFunction(string apiKey, string userInput)
{
string apiUrl = "https://api-inference.huggingface.co/models/openai-community/gpt2";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
var requestData = new { inputs = userInput };
var jsonContent = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");
try
{
var response = await client.PostAsync(apiUrl, jsonContent);
if (!response.IsSuccessStatusCode)
{
return $"Error {response.StatusCode}: {response.ReasonPhrase}";
}
var responseBody = await response.Content.ReadAsStringAsync();
var jsonResponse = JsonConvert.DeserializeObject<dynamic>(responseBody);
return jsonResponse?[0]?.generated_text?.ToString()?.Trim() ?? "No response.";
}
catch (HttpRequestException ex)
{
return $"Request error: {ex.Message}";
}
catch (Exception ex)
{
return $"Unexpected error: {ex.Message}";
}
}
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox comboBox = sender as ComboBox;
string selectedProvider = (comboBox?.SelectedItem as ComboBoxItem)?.Content?.ToString() ?? string.Empty;
if (string.IsNullOrEmpty(selectedProvider))
{
Console.WriteLine("No provider selected.");
return;
}
string apiKey = InputTextBoxApikey.Text ?? string.Empty;
}
}
public class ChatMessage
{
public string Message { get; set; }
public string Timestamp { get; set; }
}
}