-
-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathN2CLLMModule.cpp
More file actions
498 lines (427 loc) · 18.5 KB
/
N2CLLMModule.cpp
File metadata and controls
498 lines (427 loc) · 18.5 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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
// Copyright (c) 2025 Nick McClure (Protospatial). All Rights Reserved.
#include "LLM/N2CLLMModule.h"
#include "Core/N2CNodeTranslator.h"
#include "Core/N2CSerializer.h"
#include "Core/N2CSettings.h"
#include "LLM/N2CSystemPromptManager.h"
#include "LLM/N2CBaseLLMService.h"
#include "LLM/N2CLLMProviderRegistry.h"
#include "LLM/Providers/N2CAnthropicService.h"
#include "LLM/Providers/N2CDeepSeekService.h"
#include "LLM/Providers/N2CGeminiService.h"
#include "LLM/Providers/N2COpenAIService.h"
#include "LLM/Providers/N2COllamaService.h"
#include "LLM/Providers/N2COpenAICompatibleService.h"
#include "Utils/N2CLogger.h"
UN2CLLMModule* UN2CLLMModule::Get()
{
static UN2CLLMModule* Instance = nullptr;
if (!Instance)
{
Instance = NewObject<UN2CLLMModule>();
Instance->AddToRoot(); // Prevent garbage collection
Instance->CurrentStatus = EN2CSystemStatus::Idle;
Instance->LatestTranslationPath = TEXT("");
}
return Instance;
}
bool UN2CLLMModule::Initialize()
{
CurrentStatus = EN2CSystemStatus::Initializing;
// Load settings
const UN2CSettings* Settings = GetDefault<UN2CSettings>();
if (!Settings)
{
CurrentStatus = EN2CSystemStatus::Error;
FN2CLogger::Get().LogError(TEXT("Failed to load plugin settings"), TEXT("LLMModule"));
return false;
}
// Create config from settings
Config.Provider = Settings->Provider;
Config.ApiKey = Settings->GetActiveApiKey();
Config.Model = Settings->GetActiveModel();
// Initialize provider registry
InitializeProviderRegistry();
// Initialize components
if (!InitializeComponents() || !CreateServiceForProvider(Config.Provider))
{
CurrentStatus = EN2CSystemStatus::Error;
return false;
}
bIsInitialized = true;
CurrentStatus = EN2CSystemStatus::Idle;
FN2CLogger::Get().Log(TEXT("LLM Module initialized successfully"), EN2CLogSeverity::Info, TEXT("LLMModule"));
return true;
}
void UN2CLLMModule::ProcessN2CJson(
const FString& JsonInput,
const FOnLLMResponseReceived& OnComplete)
{
if (!bIsInitialized)
{
CurrentStatus = EN2CSystemStatus::Error;
FN2CLogger::Get().LogError(TEXT("LLM Module not initialized"), TEXT("LLMModule"));
const bool bExecuted = OnComplete.ExecuteIfBound(TEXT("{\"error\": \"Module not initialized\"}"));
return;
}
CurrentStatus = EN2CSystemStatus::Processing;
// Broadcast that request is being sent
OnTranslationRequestSent.Broadcast();
if (!ActiveService.GetInterface())
{
FN2CLogger::Get().LogError(TEXT("No active LLM service"), TEXT("LLMModule"));
const bool bExecuted = OnComplete.ExecuteIfBound(TEXT("{\"error\": \"No active service\"}"));
return;
}
// Get active service
TScriptInterface<IN2CLLMService> Service = GetActiveService();
if (!Service.GetInterface())
{
FN2CLogger::Get().LogError(TEXT("No active service"), TEXT("LLMModule"));
return;
}
// Check if service supports system prompts
bool bSupportsSystemPrompts = false;
FString Endpoint, AuthToken;
Service->GetConfiguration(Endpoint, AuthToken, bSupportsSystemPrompts);
// Get system prompt with language specification
const UN2CSettings* Settings = GetDefault<UN2CSettings>();
FString SystemPrompt = PromptManager->GetLanguageSpecificPrompt(
TEXT("CodeGen"),
Settings ? Settings->TargetLanguage : EN2CCodeLanguage::Cpp
);
// Connect the HTTP handler's translation response delegate to our module's delegate
if (HttpHandler)
{
HttpHandler->OnTranslationResponseReceived = OnTranslationResponseReceived;
}
// Send request through service
ActiveService->SendRequest(JsonInput, SystemPrompt, FOnLLMResponseReceived::CreateLambda(
[this](const FString& Response)
{
// Create translation response struct
FN2CTranslationResponse TranslationResponse;
// Get active service's response parser
TScriptInterface<IN2CLLMService> ActiveServiceParser = GetActiveService();
if (ActiveServiceParser.GetInterface())
{
UN2CResponseParserBase* Parser = ActiveServiceParser->GetResponseParser();
if (Parser)
{
if (Parser->ParseLLMResponse(Response, TranslationResponse))
{
CurrentStatus = EN2CSystemStatus::Idle;
// Save translation to disk
const FN2CBlueprint& Blueprint = FN2CNodeTranslator::Get().GetN2CBlueprint();
if (SaveTranslationToDisk(TranslationResponse, Blueprint))
{
FN2CLogger::Get().Log(TEXT("Successfully saved translation to disk"), EN2CLogSeverity::Info);
}
OnTranslationResponseReceived.Broadcast(TranslationResponse, true);
FN2CLogger::Get().Log(TEXT("Successfully parsed LLM response"), EN2CLogSeverity::Info);
}
else
{
CurrentStatus = EN2CSystemStatus::Error;
FN2CLogger::Get().LogError(TEXT("Failed to parse LLM response"));
OnTranslationResponseReceived.Broadcast(TranslationResponse, false);
}
}
else
{
CurrentStatus = EN2CSystemStatus::Error;
FN2CLogger::Get().LogError(TEXT("No response parser available"));
OnTranslationResponseReceived.Broadcast(TranslationResponse, false);
}
}
else
{
CurrentStatus = EN2CSystemStatus::Error;
FN2CLogger::Get().LogError(TEXT("No active LLM service"));
OnTranslationResponseReceived.Broadcast(TranslationResponse, false);
}
}));
}
bool UN2CLLMModule::InitializeComponents()
{
// Create and initialize prompt manager
PromptManager = NewObject<UN2CSystemPromptManager>(this);
if (!PromptManager)
{
FN2CLogger::Get().LogError(TEXT("Failed to create prompt manager"), TEXT("LLMModule"));
return false;
}
PromptManager->Initialize(Config);
// Note: HTTP Handler and Response Parser will be created by the specific service
return true;
}
void UN2CLLMModule::OpenTranslationFolder(bool& Success)
{
FString PathToOpen = LatestTranslationPath;
if (PathToOpen.IsEmpty())
{
FN2CLogger::Get().LogWarning(TEXT("No translation path available, opening the base path"));
Success = true;
PathToOpen = GetTranslationBasePath();
}
if (!FPaths::DirectoryExists(PathToOpen))
{
FN2CLogger::Get().LogError(FString::Printf(TEXT("Translation directory does not exist: %s \n\nOpening the base path"), *PathToOpen));
Success = true;
PathToOpen = GetTranslationBasePath();
}
#if PLATFORM_WINDOWS
FPlatformProcess::ExploreFolder(*PathToOpen);
Success = true;
#endif
#if PLATFORM_MAC
FMacPlatformProcess::ExploreFolder(*PathToOpen);
Success = true;
#endif
}
bool UN2CLLMModule::SaveTranslationToDisk(const FN2CTranslationResponse& Response, const FN2CBlueprint& Blueprint)
{
// Get blueprint name from metadata
FString BlueprintName = Blueprint.Metadata.Name;
if (BlueprintName.IsEmpty())
{
BlueprintName = TEXT("UnknownBlueprint");
}
// Generate root path for this translation
FString RootPath = GenerateTranslationRootPath(BlueprintName);
// Ensure the directory exists
if (!EnsureDirectoryExists(RootPath))
{
FN2CLogger::Get().LogError(FString::Printf(TEXT("Failed to create translation directory: %s"), *RootPath));
return false;
}
// Store the path for later reference
LatestTranslationPath = RootPath;
// Save the Blueprint JSON (pretty-printed)
FString JsonFileName = FString::Printf(TEXT("N2C_BP_%s.json"), *FPaths::GetBaseFilename(RootPath));
FString JsonFilePath = FPaths::Combine(RootPath, JsonFileName);
// Serialize the Blueprint to JSON with pretty printing
FN2CSerializer::SetPrettyPrint(true);
FString JsonContent = FN2CSerializer::ToJson(Blueprint);
if (!FFileHelper::SaveStringToFile(JsonContent, *JsonFilePath))
{
FN2CLogger::Get().LogError(FString::Printf(TEXT("Failed to save JSON file: %s"), *JsonFilePath));
return false;
}
// Save minified version of the Blueprint JSON
FString MinifiedJsonFileName = FString::Printf(TEXT("N2C_BP_Minified_%s.json"), *FPaths::GetBaseFilename(RootPath));
FString MinifiedJsonFilePath = FPaths::Combine(RootPath, MinifiedJsonFileName);
// Serialize the Blueprint to JSON without pretty printing
FN2CSerializer::SetPrettyPrint(false);
FString MinifiedJsonContent = FN2CSerializer::ToJson(Blueprint);
if (!FFileHelper::SaveStringToFile(MinifiedJsonContent, *MinifiedJsonFilePath))
{
FN2CLogger::Get().LogWarning(FString::Printf(TEXT("Failed to save minified JSON file: %s"), *MinifiedJsonFilePath));
// Continue even if minified version fails
}
// Save the raw LLM translation response JSON
FString TranslationJsonFileName = FString::Printf(TEXT("N2C_Translation_%s.json"), *FPaths::GetBaseFilename(RootPath));
FString TranslationJsonFilePath = FPaths::Combine(RootPath, TranslationJsonFileName);
// Serialize the Translation response to JSON
TSharedPtr<FJsonObject> TranslationJsonObject = MakeShared<FJsonObject>();
// Create graphs array
TArray<TSharedPtr<FJsonValue>> GraphsArray;
for (const FN2CGraphTranslation& Graph : Response.Graphs)
{
TSharedPtr<FJsonObject> GraphObject = MakeShared<FJsonObject>();
GraphObject->SetStringField(TEXT("graph_name"), Graph.GraphName);
GraphObject->SetStringField(TEXT("graph_type"), Graph.GraphType);
GraphObject->SetStringField(TEXT("graph_class"), Graph.GraphClass);
// Create code object
TSharedPtr<FJsonObject> CodeObject = MakeShared<FJsonObject>();
CodeObject->SetStringField(TEXT("graphDeclaration"), Graph.Code.GraphDeclaration);
CodeObject->SetStringField(TEXT("graphImplementation"), Graph.Code.GraphImplementation);
CodeObject->SetStringField(TEXT("implementationNotes"), Graph.Code.ImplementationNotes);
GraphObject->SetObjectField(TEXT("code"), CodeObject);
GraphsArray.Add(MakeShared<FJsonValueObject>(GraphObject));
}
TranslationJsonObject->SetArrayField(TEXT("graphs"), GraphsArray);
// Add usage information if available
if (Response.Usage.InputTokens > 0 || Response.Usage.OutputTokens > 0)
{
TSharedPtr<FJsonObject> UsageObject = MakeShared<FJsonObject>();
UsageObject->SetNumberField(TEXT("input_tokens"), Response.Usage.InputTokens);
UsageObject->SetNumberField(TEXT("output_tokens"), Response.Usage.OutputTokens);
TranslationJsonObject->SetObjectField(TEXT("usage"), UsageObject);
}
// Serialize to string with pretty printing
FString TranslationJsonContent;
TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&TranslationJsonContent);
FJsonSerializer::Serialize(TranslationJsonObject.ToSharedRef(), Writer);
if (!FFileHelper::SaveStringToFile(TranslationJsonContent, *TranslationJsonFilePath))
{
FN2CLogger::Get().LogWarning(FString::Printf(TEXT("Failed to save translation JSON file: %s"), *TranslationJsonFilePath));
// Continue even if translation JSON fails
}
// Get the target language from settings
const UN2CSettings* Settings = GetDefault<UN2CSettings>();
EN2CCodeLanguage TargetLanguage = Settings ? Settings->TargetLanguage : EN2CCodeLanguage::Cpp;
// Save each graph's files
for (const FN2CGraphTranslation& Graph : Response.Graphs)
{
// Skip graphs with empty names
if (Graph.GraphName.IsEmpty())
{
continue;
}
// Create directory for this graph
FString GraphDir = FPaths::Combine(RootPath, Graph.GraphName);
if (!EnsureDirectoryExists(GraphDir))
{
FN2CLogger::Get().LogWarning(FString::Printf(TEXT("Failed to create graph directory: %s"), *GraphDir));
continue;
}
// Save declaration file (C++ only)
if (TargetLanguage == EN2CCodeLanguage::Cpp && !Graph.Code.GraphDeclaration.IsEmpty())
{
FString HeaderPath = FPaths::Combine(GraphDir, Graph.GraphName + TEXT(".h"));
if (!FFileHelper::SaveStringToFile(Graph.Code.GraphDeclaration, *HeaderPath))
{
FN2CLogger::Get().LogWarning(FString::Printf(TEXT("Failed to save header file: %s"), *HeaderPath));
}
}
// Save implementation file with appropriate extension
if (!Graph.Code.GraphImplementation.IsEmpty())
{
FString Extension = GetFileExtensionForLanguage(TargetLanguage);
FString ImplPath = FPaths::Combine(GraphDir, Graph.GraphName + Extension);
if (!FFileHelper::SaveStringToFile(Graph.Code.GraphImplementation, *ImplPath))
{
FN2CLogger::Get().LogWarning(FString::Printf(TEXT("Failed to save implementation file: %s"), *ImplPath));
}
}
// Save implementation notes
if (!Graph.Code.ImplementationNotes.IsEmpty())
{
FString NotesPath = FPaths::Combine(GraphDir, Graph.GraphName + TEXT("_Notes.txt"));
if (!FFileHelper::SaveStringToFile(Graph.Code.ImplementationNotes, *NotesPath))
{
FN2CLogger::Get().LogWarning(FString::Printf(TEXT("Failed to save notes file: %s"), *NotesPath));
}
}
}
FN2CLogger::Get().Log(FString::Printf(TEXT("Translation saved to: %s"), *RootPath), EN2CLogSeverity::Info);
return true;
}
FString UN2CLLMModule::GenerateTranslationRootPath(const FString& BlueprintName) const
{
// Get current date/time
FDateTime Now = FDateTime::Now();
FString Timestamp = Now.ToString(TEXT("%Y-%m-%d-%H.%M.%S"));
// Create folder name
FString FolderName = FString::Printf(TEXT("%s_%s"), *BlueprintName, *Timestamp);
// Get the saved translations base path
FString BasePath = GetTranslationBasePath();
return FPaths::Combine(BasePath, FolderName);
}
FString UN2CLLMModule::GetTranslationBasePath() const
{
// Check if custom output directory is set in settings
const UN2CSettings* Settings = GetDefault<UN2CSettings>();
FString BasePath;
if (Settings && !Settings->CustomTranslationOutputDirectory.Path.IsEmpty())
{
// Use custom path if specified
BasePath = Settings->CustomTranslationOutputDirectory.Path;
FN2CLogger::Get().Log(
FString::Printf(TEXT("Using custom translation output directory: %s"), *BasePath),
EN2CLogSeverity::Info);
}
else
{
// Use default path
BasePath = FPaths::ProjectSavedDir() / TEXT("NodeToCode") / TEXT("Translations");
}
return BasePath;
}
FString UN2CLLMModule::GetFileExtensionForLanguage(EN2CCodeLanguage Language) const
{
switch (Language)
{
case EN2CCodeLanguage::Cpp:
return TEXT(".cpp");
case EN2CCodeLanguage::Python:
return TEXT(".py");
case EN2CCodeLanguage::JavaScript:
return TEXT(".js");
case EN2CCodeLanguage::CSharp:
return TEXT(".cs");
case EN2CCodeLanguage::Swift:
return TEXT(".swift");
case EN2CCodeLanguage::Pseudocode:
return TEXT(".md");
default:
return TEXT(".txt");
}
}
bool UN2CLLMModule::EnsureDirectoryExists(const FString& DirectoryPath) const
{
if (!FPaths::DirectoryExists(DirectoryPath))
{
bool bSuccess = FPlatformFileManager::Get().GetPlatformFile().CreateDirectoryTree(*DirectoryPath);
if (!bSuccess)
{
FN2CLogger::Get().LogError(
FString::Printf(TEXT("Failed to create directory: %s"), *DirectoryPath));
return false;
}
FN2CLogger::Get().Log(
FString::Printf(TEXT("Created directory: %s"), *DirectoryPath),
EN2CLogSeverity::Info);
return true;
}
return true;
}
bool UN2CLLMModule::CreateServiceForProvider(EN2CLLMProvider Provider)
{
// Get the provider registry
UN2CLLMProviderRegistry* Registry = UN2CLLMProviderRegistry::Get();
// Check if the provider is registered
if (!Registry->IsProviderRegistered(Provider))
{
FN2CLogger::Get().LogError(
FString::Printf(TEXT("Provider type not registered: %s"),
*UEnum::GetValueAsString(Provider)),
TEXT("LLMModule")
);
return false;
}
// Create the provider service
TScriptInterface<IN2CLLMService> ServiceInterface = Registry->CreateProvider(Provider, this);
if (!ServiceInterface.GetInterface())
{
FN2CLogger::Get().LogError(
FString::Printf(TEXT("Failed to create service for provider type: %s"),
*UEnum::GetValueAsString(Provider)),
TEXT("LLMModule")
);
return false;
}
// Initialize service
if (!ServiceInterface.GetInterface()->Initialize(Config))
{
FN2CLogger::Get().LogError(TEXT("Failed to initialize service"), TEXT("LLMModule"));
return false;
}
// Store active service
ActiveService = ServiceInterface;
return true;
}
void UN2CLLMModule::InitializeProviderRegistry()
{
// Get the provider registry
UN2CLLMProviderRegistry* Registry = UN2CLLMProviderRegistry::Get();
// Register all provider classes
Registry->RegisterProvider(EN2CLLMProvider::OpenAI, UN2COpenAIService::StaticClass());
Registry->RegisterProvider(EN2CLLMProvider::Anthropic, UN2CAnthropicService::StaticClass());
Registry->RegisterProvider(EN2CLLMProvider::Gemini, UN2CGeminiService::StaticClass());
Registry->RegisterProvider(EN2CLLMProvider::DeepSeek, UN2CDeepSeekService::StaticClass());
Registry->RegisterProvider(EN2CLLMProvider::Ollama, UN2COllamaService::StaticClass());
Registry->RegisterProvider(EN2CLLMProvider::OpenAICompatible, UN2COpenAICompatibleService::StaticClass());
FN2CLogger::Get().Log(TEXT("Provider registry initialized"), EN2CLogSeverity::Info, TEXT("LLMModule"));
}