Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
188 lines (154 loc) · 6.19 KB
/
Copy pathProgram.cs
File metadata and controls
188 lines (154 loc) · 6.19 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
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace GciLocal;
// ------------------------------------------------------------------
// GCI local para DCS
//
// Loop:
// 1. Lee el archivo stats.json que genera LotATC (dump_json_stats = true)
// 2. Arma un prompt con esa info + instrucciones de "hablar como GCI"
// 3. Se lo manda a un modelo corriendo en Ollama (local, sin internet)
// 4. Imprime la respuesta en consola
//
// Todavia NO incluye texto-a-voz ni conexion a SRS: eso va en el
// proximo paso una vez que confirmemos que esta parte anda bien.
// ------------------------------------------------------------------
internal class Program
{
private static readonly HttpClient Http = new();
private static readonly AppSettings Settings = LoadSettings();
private static async Task Main()
{
Console.WriteLine("GCI local iniciado. Ctrl+C para salir.");
Console.WriteLine($"Leyendo: {Settings.StatsJsonPath}");
Console.WriteLine($"Modelo: {Settings.Model}");
Console.WriteLine();
string? ultimoContenido = null;
while (true)
{
try
{
if (!File.Exists(Settings.StatsJsonPath))
{
Console.WriteLine("[!] No se encuentra stats.json todavia. " +
"Revisa que LotATC este corriendo y que " +
"dump_json_stats este en true.");
}
else
{
string contenido = LeerStatsJsonSeguro(Settings.StatsJsonPath, Settings.MaxJsonCharacters);
// Evita gastar tokens si el archivo no cambio desde la ultima vez
if (contenido != ultimoContenido && !string.IsNullOrWhiteSpace(contenido))
{
ultimoContenido = contenido;
string prompt = ArmarPrompt(contenido);
string respuesta = await ConsultarOllama(prompt);
Console.WriteLine($"[GCI] {respuesta.Trim()}");
Console.WriteLine();
}
}
}
catch (Exception ex)
{
Console.WriteLine($"[error] {ex.Message}");
}
await Task.Delay(TimeSpan.FromSeconds(Settings.IntervalSeconds));
}
}
private static AppSettings LoadSettings()
{
string appSettingsPath = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
if (!File.Exists(appSettingsPath))
{
throw new FileNotFoundException(
"No se encontró appsettings.json junto al ejecutable. Copialo al directorio de salida o al directorio del proyecto.",
appSettingsPath);
}
string json = File.ReadAllText(appSettingsPath);
var settingsFile = JsonSerializer.Deserialize<SettingsFile>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
var settings = settingsFile?.GciLocal;
if (settings is null)
{
throw new InvalidOperationException("El archivo appsettings.json no contiene una configuración válida.");
}
return settings;
}
// LotATC puede estar escribiendo el archivo justo cuando lo leemos,
// asi que abrimos con FileShare.ReadWrite para no chocar con eso.
private static string LeerStatsJsonSeguro(string path, int maxCharacters)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var reader = new StreamReader(stream);
string contenido = reader.ReadToEnd();
if (contenido.Length > maxCharacters)
{
contenido = contenido[..maxCharacters];
}
return contenido;
}
private static string ArmarPrompt(string statsJson)
{
return $"""
Sos un controlador GCI (Ground Control Intercept) de DCS World.
Te paso un extracto del JSON con la situacion tactica actual
(contactos de radar, posiciones, coalicion, etc).
Reglas:
- Respondé en español, corto (2-3 frases maximo).
- Usá formato de llamada real de radio: rumbo, distancia, altitud
cuando la info este disponible.
- Priorizá el contacto mas relevante o amenazante si hay varios.
- Si no hay contactos relevantes, decilo en una sola frase.
- No expliques el JSON ni menciones que es un JSON.
Datos:
{statsJson}
""";
}
private static async Task<string> ConsultarOllama(string prompt)
{
var body = new OllamaRequest
{
Model = Settings.Model,
Prompt = prompt,
Stream = false
};
HttpResponseMessage resp = await Http.PostAsJsonAsync(Settings.OllamaUrl, body);
resp.EnsureSuccessStatusCode();
var data = await resp.Content.ReadFromJsonAsync<OllamaResponse>();
return data?.Response ?? "(sin respuesta del modelo)";
}
private class AppSettings
{
[JsonPropertyName("StatsJsonPath")]
public string StatsJsonPath { get; set; } = "";
[JsonPropertyName("IntervalSeconds")]
public int IntervalSeconds { get; set; } = 15;
[JsonPropertyName("OllamaUrl")]
public string OllamaUrl { get; set; } = "http://localhost:11434/api/generate";
[JsonPropertyName("Model")]
public string Model { get; set; } = "llama3.1:8b";
[JsonPropertyName("MaxJsonCharacters")]
public int MaxJsonCharacters { get; set; } = 6000;
}
private class SettingsFile
{
public AppSettings? GciLocal { get; set; }
}
private class OllamaRequest
{
[JsonPropertyName("model")]
public string Model { get; set; } = "";
[JsonPropertyName("prompt")]
public string Prompt { get; set; } = "";
[JsonPropertyName("stream")]
public bool Stream { get; set; }
}
private class OllamaResponse
{
[JsonPropertyName("response")]
public string? Response { get; set; }
}
}