-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.pas
1494 lines (1378 loc) · 52.1 KB
/
main.pas
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Menus, ComCtrls,
ExtCtrls, fpjson, jsonparser, opensslsockets,OptionsForm,
stdctrls, Buttons, HtmlView, lclintf,LCLType,
request,neuroengineapi,Math,llama,chat,StrUtils,IniFiles, Types;
type
//---------------------------------------------------------------------------
// TForm1 - Main Form of Neurochat
// Author: aortega
// Description: Represents the main window of our application containing various
// UI components required for interaction with end-users.
//---------------------------------------------------------------------------
TForm1 = class(TForm)
UpBtn: TBitBtn;
BitBtnSearchLeft: TBitBtn;
BitBtnSearchRight: TBitBtn;
BitBtnSearchClose: TBitBtn;
CheckBoxSearchCase: TCheckBox;
EditSearch: TEdit;
GroupBoxSearch: TGroupBox;
MainMenu1: TMainMenu;
Edit1: TMemo;
MenuItem1: TMenuItem;
MenuItem10: TMenuItem;
MenuItem12: TMenuItem;
MenuItem14: TMenuItem;
MenuItem23: TMenuItem;
MenuItem24: TMenuItem;
MenuItem25: TMenuItem;
MenuItem26: TMenuItem;
MenuItem7: TMenuItem;
MenuItemSendTo: TMenuItem;
MenuItemHelp: TMenuItem;
MenuItem18: TMenuItem;
MenuItem20: TMenuItem;
MenuItem21: TMenuItem;
MenuItemPZ200: TMenuItem;
MenuItemPZ150: TMenuItem;
MenuItemPZ100: TMenuItem;
MenuItemPZ50: TMenuItem;
MenuItemPZ25: TMenuItem;
MenuItemZ25: TMenuItem;
MenuItemZ50: TMenuItem;
MenuItemZ100: TMenuItem;
MenuItemZ150: TMenuItem;
MenuItemZ200: TMenuItem;
MenuItemCloseTab: TMenuItem;
MenuItemFind: TMenuItem;
MenuItemOpenAI: TMenuItem;
MenuItemCustomPersonality: TMenuItem;
MenuItemMainNe: TMenuItem;
MenuItem22: TMenuItem;
MenuItemSaveAs: TMenuItem;
MenuItem13: TMenuItem;
MenuItemDefaultPersonality: TMenuItem;
MenuItemAssistantPersonality: TMenuItem;
MenuItemBasedPersonality: TMenuItem;
MenuItemC3POersonality: TMenuItem;
MenuItemBorgesPersonality: TMenuItem;
MenuItemCoderPersonality: TMenuItem;
MenuItemOptions1: TMenuItem;
MenuItemOptions: TMenuItem;
MenuItem11: TMenuItem;
MenuItemResetChat: TMenuItem;
MenuItemCopy: TMenuItem;
MenuItemReset: TMenuItem;
MenuItem16: TMenuItem;
MenuNeuroengine: TMenuItem;
MenuItem2: TMenuItem;
MenuItem3: TMenuItem;
MenuItem4: TMenuItem;
MenuItem5: TMenuItem;
MenuItem6: TMenuItem;
MenuItem8: TMenuItem;
MenuItem9: TMenuItem;
OpenDialog1: TOpenDialog;
OpenDialogText: TOpenDialog;
PageControl1: TPageControl;
Panel1: TPanel;
PopupMenu1: TPopupMenu;
SaveDialog1: TSaveDialog;
Separator2: TMenuItem;
Separator3: TMenuItem;
Separator4: TMenuItem;
Separator5: TMenuItem;
Timer1: TTimer;
// Simple Chats
procedure AddNeuroengineChat(ServiceIndex:Integer);
procedure BitBtn1Click(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure LoadModelFromFile(Chat: TChat;Model:string);
procedure AddLLamaCPPChat(Model:string);
procedure AddChatGPTChat(Model:string);
procedure BitBtnSearchCloseClick(Sender: TObject);
procedure BitBtnSearchLeftClick(Sender: TObject);
procedure BitBtnSearchRightClick(Sender: TObject);
function engineNameToIndex(eName:string): Integer;
//
procedure ConnectNeuroengine();
procedure EditSearchKeyPress(Sender: TObject; var Key: char);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure Log(str: String);
procedure AddLLM(LLM: string; serviceIndex: Integer);
procedure MenuItem10Click(Sender: TObject);
procedure MenuItem12Click(Sender: TObject);
procedure MenuItem21Click(Sender: TObject);
procedure MenuItemHelpClick(Sender: TObject);
procedure MenuItem19Click(Sender: TObject);
procedure MenuItem23Click(Sender: TObject);
procedure MenuItem6Click(Sender: TObject);
procedure MenuItem9Click(Sender: TObject);
procedure MenuItemAssistantPersonalityClick(Sender: TObject);
procedure MenuItemBasedPersonalityClick(Sender: TObject);
procedure MenuItemCoderPersonalityClick(Sender: TObject);
procedure MenuItemCloseTabClick(Sender: TObject);
procedure MenuItemCustomPersonalityClick(Sender: TObject);
procedure MenuItemDefaultPersonalityClick(Sender: TObject);
procedure MenuItemC3POersonalityClick(Sender: TObject);
procedure MenuItemBorgesPersonalityClick(Sender: TObject);
procedure MenuItemMainNeClick(Sender: TObject);
procedure MenuItem4Click(Sender: TObject);
procedure MenuItemOpenAIClick(Sender: TObject);
procedure MenuItemSaveAsClick(Sender: TObject);
procedure MenuItemZ100Click(Sender: TObject);
procedure MenuItemZ150Click(Sender: TObject);
procedure MenuItemZ200Click(Sender: TObject);
procedure MenuItemZ25Click(Sender: TObject);
procedure MenuItemZ50Click(Sender: TObject);
procedure MenuNeuroengineClick(Sender: TObject);
procedure MenuItem7Click(Sender: TObject);
procedure MenuItemOptionsClick(Sender: TObject);
procedure PageControl1CloseTabClicked(Sender: TObject);
procedure PageControl1ContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
procedure refreshHtml(Chat:TChat);
procedure sendTextToAI(Chat: TChat;txt:String);
procedure InitForm(autosave:Boolean;maxCtxLen:Integer);
procedure FormCreate(Sender: TObject);
procedure LabeledEdit1KeyPress(Sender: TObject; var Key: char);
procedure MenuItemCopyClick(Sender: TObject);
procedure MenuItem16Click(Sender: TObject);
procedure MenuItemResetClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure SendToClick(Sender: TObject);
procedure UpBtnClick(Sender: TObject);
private
connected:boolean;
neuroEngines: array of TNeuroengineService;
currentzoom:Integer;
currentChatLoading:TChat;
procedure CreateConfigDir;
procedure setHtmlSize(size:Integer);
public
const
version: String = '0.6-dev';
end;
{ Defines a custom tab sheet component that maintains a relation
with instances of the TChat class. Inherits functionality from the
standard VCL TTabSheet component. }
TChatTabSheet = class(TTabSheet)
private
{ Declares a private field holding a reference to a TChat instance. }
FChat: TChat;
public
{ Provides external accessibility to the internal FChat field via
a public property. }
property Chat: TChat read FChat write FChat;
{ Overrides the default destructor inherited from the base class
to perform additional clean-up tasks before freeing the object. }
destructor Destroy; override;
end;
var
Form1: TForm1;
LoadingVar: Integer;
implementation
{$R *.lfm}
{
Performs cleanup tasks related to the current instance of TChatTabSheet.
Frees allocated resources such as the Llama model and its associated thread,
followed by releasing the Chat object itself.
Finally invokes the parent class's destructor.
}
destructor TChatTabSheet.Destroy;
begin
if Chat.llamagguf<>nil then
begin
if self.Chat.requestThread<>nil then
self.Chat.terminateRequestThread();
llama_free_model(FChat.llamagguf);
end;
Chat.Free;
inherited Destroy;
end;
{ TForm1 }
{
Dynamically generates and appends new menu items representing each available model/service
obtained from the connected Neuroengine platform.
These menu items include specific actions tied to their respective OnClick events.
@param LLM [string]: Name of the model/service to add as a menu item.
@param serviceIndex [integer]: Index number assigned to the particular model/service.
}
procedure TForm1.AddLLM(LLM: string; serviceIndex: Integer);
var
AddMenuItem:TMenuItem;
begin
// Create a new menu item with the desired name and action
AddMenuItem := TMenuItem.Create(Self);
AddMenuItem.Caption := LLM;
AddMenuItem.Tag := serviceIndex;
AddMenuItem.OnClick:=@MenuNeuroengineClick;
// Assign the newly created menu item to popup and main menu items
MenuNeuroengine.Add(AddMenuItem);
// Create a new menu item with the desired name and action
AddMenuItem := TMenuItem.Create(Self);
AddMenuItem.Caption := LLM;
AddMenuItem.Tag := serviceIndex;
AddMenuItem.OnClick:=@MenuNeuroengineClick;
MenuItemMainNe.Add(AddMenuItem);
end;
{
Attempts connecting to the specified API endpoint using provided JSON data.
Upon successful connection, retrieves available models/services information and
populates corresponding class properties accordingly.
Also adds menu items based on received details.
@param None
}
procedure TForm1.ConnectNeuroengine();
var
JSONToSend: string;
RegularStr: UnicodeString;
LLMName,LLMComment,LLMPreprompt,LLMEndprompt,LLMOperator: String;
JSONData: TJSONData;
I: Integer;
LogString:string;
begin
Log('Configuration directory is '+ GetAppConfigDir(False));
self.Log('Connecting to neuroengine...');
// Prepare the JSON data to send in the POST request
JSONToSend := '{"command": "getmodels"}'; // Replace with your JSON data
try
RegularStr:=QueryAPI('',JSONToSend);
if (RegularStr='') then begin
log('Cannot connect to Neuroengine.ai site.');
exit;
end;
self.connected:=True;
self.Log('Connected. Requesting model list...');
// Parse the regular string as JSON data
JSONData := GetJSON(RegularStr);
// Allocate memory for storage
SetLength(neuroEngines, TJSONArray(JSONData).Count);
LogString:='';
for I := 0 to TJSONArray(JSONData).Count - 1 do
begin
// Store service info
LLMName := TJSONObject(TJSONArray(JsonData).Items[I]).Find('name').AsString;
LLMComment := TJSONObject(TJSONArray(JsonData).Items[I]).Find('comment').AsString;
LLMPreprompt := TJSONObject(TJSONArray(JsonData).Items[I]).Find('preprompt').AsString;
LLMEndprompt := TJSONObject(TJSONArray(JsonData).Items[I]).Find('endprompt').AsString;
LLMOperator := TJSONObject(TJSONArray(JsonData).Items[I]).Find('operator').AsString;
// Add services
self.neuroEngines[I].name := LLMName;
self.neuroEngines[I].preprompt := LLMPreprompt;
self.neuroEngines[I].endprompt := LLMEndprompt;
self.neuroEngines[I].oper := LLMOperator;
self.neuroEngines[I].comment := LLMComment;
// Add Menu items
LogString:=LogString+' '+LLMName+',';
self.AddLLM(LLMName,I);
end;
// Clean up
JSONData.Free;
self.Log('Found '+LogString);
Log(self.neuroEngines[0].comment);
except
on E: Exception do
log('Cannot connect to Neuroengine.ai site: '+ E.Message);
end;
end;
{
Intercepts ENTER and ESC keys pressed inside EditSearch text box.
When ENTER is hit, triggers BitBtnSearchRight click action which typically
initiates search operation. Hides GroupBoxSearch containing edit field when ESC is pressed.
}
procedure TForm1.EditSearchKeyPress(Sender: TObject; var Key: char);
begin
if (Key = #13) then // Enter key is represented by ASCII value of 13, so check for it here.
begin
self.BitBtnSearchRight.Click;
end;
if (Key = #27) then // ESC
begin
self.GroupBoxSearch.Visible:=False;
end
end;
{
Serializes all existing conversation histories into a single JSON string before
saving them to a local .neurochat.history file.
This ensures that future application launches are able to restore these sessions correctly.
}
procedure TForm1.FormDestroy(Sender: TObject);
var
Chat: TChat;
i: Integer;
jsonString:string;
f: TFileStream;
root:TJSONObject;
chatArray: TJSONArray;
sFileName:String;
begin
sFileName := GetAppConfigDir(False)+'/.neurochat.history';
root := TJSONObject.Create;
chatArray := TJSONArray.Create;
for i:=0 to PageControl1.PageCount-1 do
begin
Chat:=TChatTabSheet(PageControl1.Page[i]).Chat;
chatArray.Add(Chat.toJson)
end;
root.Add('Chats',chatArray);
jsonString:=root.FormatJSON();
// Open the file for output (creating if not exists)
f := TFileStream.Create(sFileName, fmCreate);
try
f.Write(PAnsiChar(jsonString)^,Length(jsonString));
finally
f.Free;
root.Free;
end;
end;
{
Loads previous conversations from JSON files saved locally.
If no valid JSON is found or 'autosave' flag is false, creates a blank slate instead.
Each loaded chat object gets associated with a new Tab Sheet within Page Control component.
@param autosave [Boolean]: Flag determining whether previously saved chats need to be restored.
@param maxCtxLen [Integer]: Maximum context length value read from the INI file.
}
procedure TForm1.InitForm(autosave:Boolean;maxCtxLen:Integer);
var
sFileName:String;
Fs: TFileStream;
P: TJSONParser;
J: TJSONData;
chatArray: TJSONArray;
chatjs:TJSONObject;
chat:TChat;
i:Integer;
NewTabSheet: TChatTabSheet;
begin
sFileName := GetAppConfigDir(False)+'/.neurochat.history';
if (not FileExists(sFileName)) or (not autosave) then
self.AddNeuroengineChat(-1)
else begin
try
Fs := TFileStream.Create(sFileName, fmopenRead);
except
self.AddNeuroengineChat(-1);
Log('Can''t open history file at '+sFileName);
exit;
end;
try
P := TJSONParser.Create(Fs);
try
J := P.Parse;
if Assigned(J) then
begin
chatArray:= TJSONArray(J.FindPath('Chats'));
for I := 0 to chatArray.Count -1 do
try
chatjs:=TJSONObject(chatArray[I]);
chat:=TChat.FromJSON(chatjs);
// Add a new tab sheet to the page control
NewTabSheet := TChatTabSheet.Create(PageControl1);
NewTabSheet.BorderStyle:=bsNone;
NewTabSheet.PageControl:=PageControl1;
NewTabSheet.Caption:=ExtractFileName(chat.ServiceName);
NewTabSheet.Tag:=0;
chat.max_context_len:=maxCtxLen;
// Allocate new ChatStruct
Chat.HtmlViewer := THtmlViewer.Create(NewTabSheet);
Chat.HtmlViewer.BorderStyle:=htNone;
Chat.HtmlViewer.Parent:=NewTabSheet;
Chat.HtmlViewer.Align:=TAlign.alClient;
Chat.HtmlViewer.DefFontSize:=self.currentzoom;
NewTabSheet.Chat:=chat;
// Chat.HTMLViewer.ScrollBars:=ssVertical;
NewTabSheet.AutoSize:=false;
Chat.HTMLViewer.AutoSize:=false;
chat.refreshHtml();
Application.HandleMessage;
except
end;
end;
finally
P.Free;
end;
finally
Fs.Free;
end;
end;
end;
{
Initializes properties when creating the form instance. Reads configuration values
stored in neurochat.ini related to auto-save functionality, default zoom level,
maximum context length limit, and initial UI state. Sets up GUI components accordingly.
}
procedure TForm1.FormCreate(Sender: TObject);
var
IniFile: TIniFile;
begin
self.connected:=False;
self.KeyPreview:=True;
try
CreateConfigDir;
IniFile := TIniFile.Create(GetAppConfigDir(False)+'/.neurochat.ini');
except
Log('Can''t create config file');
exit;
end;
{Read config file}
try
{Read zoom settings}
currentZoom:=IniFile.ReadInteger('Common','zoom',12);
self.setHtmlSize(currentZoom);
{Set zoom menu check}
case currentZoom of
8: begin
self.MenuItemPZ25.Checked:=True;
self.MenuItemZ25.Checked:=True;
end;
10: begin
self.MenuItemPZ50.Checked:=True;
self.MenuItemZ50.Checked:=True;
end;
12: begin
self.MenuItemPZ100.Checked:=True;
self.MenuItemZ100.Checked:=True;
end;
15: begin
self.MenuItemPZ150.Checked:=True;
self.MenuItemZ150.Checked:=True;
end;
20: begin
self.MenuItemPZ200.Checked:=True;
self.MenuItemZ200.Checked:=True;
end;
end;
edit1.TextHint:='Write your message here';
finally
IniFile.Free;
end;
end;
{
Monitors keyboard inputs while focused on Form1. Handles specific combinations
like CTRL + F, CTRL + C and ESC keys with corresponding actions.
Terminates ongoing AI request threads upon pressing ESC.
@param Sender [TObject]: Object responsible for triggering the event.
@param Key [Word]: Numeric code assigned to the detected keystroke.
@param Shift [TShiftState]: Enum indicating active modifier keys during the event.
}
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
Chat: TChat;
begin
// Handle ctrl+f
if (ssCtrl in Shift) and (Ord('F')=Key) then
begin
self.GroupBoxSearch.Visible:=True;
self.EditSearch.SetFocus;
end;
// Handle ctrl+c
if (ssCtrl in Shift) and (Ord('C')=Key) then
begin
self.MenuItemCopyClick(nil);
end;
if (Key = VK_ESCAPE) then // ESC
begin
Chat:=TChatTabSheet(PageControl1.ActivePage).Chat;
if Chat.requestThread<>nil then
Chat.requestThread.Terminate;
end
end;
{
Constructs a Vicuna-styled chat prompt using given parameters such as conversation history,
prefixes, suffixes, and maximum context length. Returns the finalized prompt as a single string.
@param chat [TStrings]: Collection of strings representing individual chat entries.
@param preprompt [String]: Prefix to be applied at the beginning of the constructed prompt.
@param endprompt [String]: Delimiter inserted between each entry in the constructed prompt.
@param maxContext [Integer]: Maximum allowed number of characters in the resulting prompt.
}
// Build vicuna-style chat
function buildChatPrompt(chat: Tstrings;preprompt:String;endprompt:String;maxContext:Integer) : string;
var
prompt: string;
pre:string;
i: Integer;
begin
prompt:=#10+endprompt;
for i:=chat.Count downto 1 do
begin
if StartsStr('User: ',chat[i-1]) then
pre:=#10
else pre:=#10+endprompt;
if length(pre+chat[i-1]+prompt)>=maxContext*2 then
break;
prompt:=pre+chat[i-1]+prompt;
end;
buildChatPrompt:=preprompt+prompt;
end;
{
Updates the visual appearance of the provided HTML viewer based on its underlying data structure. Scrolls the viewport to the bottom allowing users to see newly generated content immediately.
@param Chat [TChat]: Instance of the chat session whose HTML Viewer should be updated.
}
procedure TForm1.refreshHtml(Chat:TChat);
begin
Chat.refreshHtml();
Chat.HTMLViewer.Position:=Chat.HTMLViewer.MaxVertical;
end;
{
Prepares and initiates request to send user-provided text to the appropriate AI backend.
Creates a prompt string containing previous messages and custom prefix/suffix prompts defined in Personality settings.
Cancels existing requests prior to starting a new one.
@param Chat [TChat]: Instance of the chat session being updated.
@param txt [String]: Input text submitted by the user.
}
procedure TForm1.sendTextToAI(Chat: TChat;txt:String);
begin
if Chat.ServiceType = AIT_LlamaCPP then
begin
if Chat.llamagguf = nil then
self.LoadModelFromFile(Chat,Chat.ServiceName);
if Chat.llamagguf = nil then
begin
self.Log('Failed to load model from '+Chat.ServiceName);
exit;
end;
end;
Chat.outhtml.Add('### User: '+txt);
Chat.outhtml.Add('AI is typing...');
Chat.Chatlines.Add('User: '+txt);
if (Chat.requestThread<>Nil) then // cancel current thread
Chat.terminateRequestThread();
// Request thread
Chat.createRequestThread();
Chat.requestThread.PromptToAnswer:=buildChatPrompt(Chat.chatlines,Chat.Personality.preprompt,Chat.Personality.endprompt,Chat.max_context_len);
Chat.requestThread.Start;
end;
{
Intercepts ENTER key press events within Edit1 component. When triggered, sends entered text to the connected AI,
clears Edit1 field, and refreshes the current chat tab's HtmlViewer component.
}
procedure TForm1.LabeledEdit1KeyPress(Sender: TObject; var Key: char);
begin
if (Key = #13) then // Enter key is represented by ASCII value of 13, so check for it here.
begin
if ((GetKeyState(VK_SHIFT) and $8000) <> 0) then {SHFT pressed}
exit;
self.UpBtnClick(Sender);
Key := #0;
end;
end;
{
Appends a message to the output text area of the currently selected chat tab. Automatically refreshes the HtmlViewer component after updating.
@param str [String]: Text to be added into the chat window.
}
procedure TForm1.Log(str: String);
var
Chat: TChat;
begin
if (PageControl1.ActivePage=Nil) then
exit;
Chat:=TChatTabSheet(PageControl1.ActivePage).Chat;
Chat.outhtml.Add('<SYSTEM> '+str);
self.refreshHtml(Chat);
end;
{
Copies the content of the currently selected chat tab's HtmlViewer component to clipboard.
}
procedure TForm1.MenuItemCopyClick(Sender: TObject);
var
ChatTabSheet: TChatTabSheet;
begin
ChatTabSheet:=TChatTabSheet(PageControl1.ActivePage);
ChatTabSheet.FChat.HtmlViewer.CopyToClipboard;
end;
procedure TForm1.MenuItem16Click(Sender: TObject);
begin
self.GroupBoxSearch.Visible:=True;
self.EditSearch.SetFocus;
end;
{
Clears all chat lines and output text in currently selected chat tab. Refreshes the associated HtmlViewer component.
}
procedure TForm1.MenuItemResetClick(Sender: TObject);
var
ChatTabSheet: TChatTabSheet;
begin
//self.PageControl1.ActivePage;
ChatTabSheet:=TChatTabSheet(PageControl1.ActivePage);
ChatTabSheet.FChat.Chatlines.Clear;
ChatTabSheet.Chat.outhtml.Clear;
self.refreshHtml(ChatTabSheet.FChat);
end;
{
Function executed periodically when timer expires. Maintains connections and updates UI components displaying AI responses.
}
procedure TForm1.Timer1Timer(Sender: TObject);
var
Chat: TChat;
i:Integer;
begin
if self.connected=False then
begin
self.connected:=true;
self.InitForm(settings.CheckBoxAutosave.Checked,StrToIntDef(settings.LabeledEditMaxLen.Text,1024));
self.ConnectNeuroengine();
if length(self.neuroEngines)>0 then
log('Connected successfuly. Ready to chat.')
else
log('Check your internet connection.');
exit;
end;
for i := 0 to PageControl1.PageCount - 1 do
begin
Chat:=TChatTabSheet(PageControl1.Pages[i]).Chat;
if Chat.requestThread<>Nil then
begin
if Length(Chat.requestThread.Response)>0 then
begin
Chat.outhtml.Delete(Chat.outhtml.Count-1);
Chat.outhtml.Add(Chat.requestThread.Response);
Chat.Chatlines.Add(Chat.requestThread.Response);
Chat.requestThread.Response:='';
Chat.requestThread.Free;
Chat.requestThread:=Nil;
self.refreshHtml(Chat);
end;
if Chat.requestThread<>nil then
if Length(Chat.requestThread.PartialAnswer)>0 then
begin
Chat.HtmlViewer.DoubleBuffered:=False;
Chat.outhtml.Delete(Chat.outhtml.Count-1);
Chat.outhtml.Add(Chat.requestThread.PartialAnswer);
self.refreshHtml(Chat);
end;
end;
end;
end;
procedure TForm1.CreateConfigDir;
var
DirectoryPath: string;
begin
// Specify the directory path you want to create
DirectoryPath := GetAppConfigDir(False);
// Check if the directory exists
if not DirectoryExists(DirectoryPath) then
begin
// If it doesn't exist, attempt to create it and its parent directories
if not ForceDirectories(DirectoryPath) then
begin
// Handle the error if unable to create the directory
writeln('Failed to create directory: ', DirectoryPath);
// Handle the error appropriately for your application
end;
end;
end;
{Procedure adding a NeuroEngine chat tab with specified service by index}
procedure TForm1.AddNeuroengineChat(ServiceIndex:Integer);
var
NewTabSheet: TChatTabSheet;
Chat: TChat;
ServiceName: string;
IniFile:TIniFile;
maxCtxLen:Integer;
begin
if ServiceIndex=-1 then
ServiceName:='Mixtral-7b-8expert'
else ServiceName:= self.neuroEngines[ServiceIndex].name;
// Add a new tab sheet to the page control
NewTabSheet := TChatTabSheet.Create(PageControl1);
NewTabSheet.BorderStyle:=bsNone;
NewTabSheet.PageControl:=PageControl1;
NewTabSheet.Caption:=ServiceName;
NewTabSheet.Tag:=ServiceIndex;
// Allocate new ChatStruct
IniFile := TIniFile.Create(GetAppConfigDir(False)+'/.neurochat.ini');
try
{Read maxlen settings}
maxCtxLen:=IniFile.ReadInteger('Common','max_new_len',1024);
finally
IniFile.Free;
end;
Chat:= TChat.Create(ServiceName,AIT_Neuroengine,'#EBF5FB',maxCtxLen);
//Chat.ServiceIndex:=ServiceIndex;
if ServiceIndex>=0 then
begin
Chat.Personality.preprompt:=self.neuroEngines[ServiceIndex].preprompt;
Chat.Personality.endprompt:=self.neuroEngines[ServiceIndex].endprompt;
end;
Chat.HtmlViewer := THtmlViewer.Create(NewTabSheet);
Chat.HtmlViewer.BorderStyle:=htNone;
Chat.HtmlViewer.Parent:=NewTabSheet;
Chat.HtmlViewer.ScrollBars:=ssVertical;
Chat.HtmlViewer.Align:=TAlign.alClient;
Chat.HtmlViewer.DefFontSize:=self.currentzoom;
NewTabSheet.Chat:=Chat;
PageControl1.ActivePage:=NewTabSheet;
if ServiceIndex>=0 then
Log(self.neuroEngines[ServiceIndex].comment);
end;
{Open a text file and add it to the prompt}
procedure TForm1.BitBtn1Click(Sender: TObject);
var
inputFile: Text;
StringList:TStringList;
fileLine: UnicodeString;
begin
if OpenDialogText.Execute then
begin
system.Assign(inputFile, self.OpenDialogText.FileName);
system.Reset(inputFile);
// Read each line of the text file and append it to the fileContents string variable
StringList := TStringList.Create;
try
while not Eof(inputFile) do
begin
ReadLn(inputFile, fileLine);
StringList.Add(fileLine);
end;
system.Close(inputFile);
self.Edit1.Lines.AddStrings(StringList);
finally
// Free the TStringList
StringList.Free;
end;
end else
self.Log('No file selected.');
exit;
end;
procedure TForm1.Edit1Change(Sender: TObject);
var
BMP:TBitmap;
LineHeight,TotalHeight:Integer;
begin
if self.Edit1.Tag<>Edit1.Lines.Count then
begin
{Calculate memo height}
BMP:=TBitMap.Create;
TRY
BMP.Canvas.Font.Assign(Edit1.Font);
LineHeight:=BMP.Canvas.TextHeight('Wq');
TotalHeight:=Edit1.Lines.Count;
if (TotalHeight>30) then TotalHeight:=30;
if (TotalHeight<2) then TotalHeight:=2;
TotalHeight:=TotalHeight*LineHeight;
Edit1.Height:=TotalHeight;
if (Length(self.Edit1.Text)>0) then
self.UpBtn.Enabled:=True
else self.UpBtn.Enabled:=False;
FINALLY
FreeAndNIL(BMP)
END;
end;
self.Edit1.Tag:=Edit1.Lines.Count;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
self.Edit1.SetFocus;
end;
{
Event handler function that receives progress updates during the model loading
phase via callback mechanism. This method calculates the percentage of completed work
and visually reflects its advancement within the active chat session's loading bar element.
}
procedure LlamaLoadCallback(progress:single; ctx:pointer);cdecl;
var
Chat: TChat;
cap:String;
percent:Integer;
begin
if (Form1.currentChatLoading=Nil) then
exit;
Chat:=Form1.currentChatLoading;
LoadingVar:=LoadingVar+1;
{Draw loading bar}
if (LoadingVar>20) then
begin
Chat.outhtml.Delete(Chat.outhtml.Count-1);
cap:='Loading...'+IntToStr(Round(progress*100))+'%';
percent:= Round((0.2+progress)*83);
Chat.outhtml.Add('<table width=100% style="border: 2px solid black; color: #ffffff;"><tr><td style="width: '+IntToStr(percent)+'%; background-color: black;" valign="top">'+cap+'</td><td style="background-color: transparent;width: '+IntToStr(100-percent)+'%;" valign="top"></td></tr></table>');
Form1.refreshHtml(Chat);
Application.HandleMessage;
LoadingVar:=0;
end
end;
{
Loads a specific LLAMA language model residing in a designated file using the
supplied Chat instance. Before initiating the actual loading process,
it prepares the environment by enabling exception handling and fine-tuning parameters based on user preferences,
e.g., GPU layer count.
}
procedure TForm1.LoadModelFromFile(Chat: TChat;Model:string);
begin
SetExceptionMask(GetExceptionMask + [exOverflow,exZeroDivide,exInvalidOp]); // God dammit, llama.cpp
llama_backend_init(False);
Chat.Params := llama_model_default_params;
self.currentChatLoading:=Chat;
Chat.Params.progress_callback:=@LlamaLoadCallback;
{GPU support}
if Settings.CheckBoxGPU.Checked then
Chat.Params.n_gpu_layers:=StrToIntDef(Settings.ComboBoxGPULayers.Text,2048)
else Chat.Params.n_gpu_layers:=0;
Form1.log('Loading '+Model);
Application.HandleMessage;
Chat.llamagguf := llama_load_model_from_file(PChar(Model), Chat.Params);
if Chat.llamagguf = nil then
begin
log('Failed to load model '+Model);
exit;
end
else begin
Chat.outhtml.Delete(Chat.outhtml.Count-1);
log('Model '+ExtractFileName(Model)+' loaded. <b>Ready to chat.</b>');
end
end;
{
Constructs a new tab sheet dedicated to hosting a LLAMA-based chat interface inside
the primary PageControl component.
}
procedure TForm1.AddLLamaCPPChat(Model:string);
var
NewTabSheet: TChatTabSheet;
Chat: TChat;
maxContextLen: Integer;
begin
// Allocate new ChatStruct
{Max LLama.cpp ctx?}
maxContextLen:=Min(512,StrToIntDef(Settings.LabeledEditMaxLen.Text,1024));
Chat:= TChat.Create(Model,AIT_LlamaCPP,'#ffefd1',maxContextLen);
// Load GGUF
LoadingVar:=0;
// Add a new tab sheet to the page control
NewTabSheet := TChatTabSheet.Create(PageControl1);
NewTabSheet.BorderStyle:=bsNone;
NewTabSheet.PageControl:=PageControl1;
NewTabSheet.Caption:=ExtractFileName(Model);
NewTabSheet.Chat:=Chat;
PageControl1.ActivePage:=NewTabSheet;
Chat.ServiceName:=Model;//ExtractFileName(Model);
Chat.HtmlViewer := THtmlViewer.Create(NewTabSheet);
Chat.HtmlViewer.BorderStyle:=htNone;
Chat.HtmlViewer.Parent:=NewTabSheet;
Chat.HtmlViewer.ScrollBars:=ssVertical;
Chat.HtmlViewer.Align:=TAlign.alClient;
Chat.HtmlViewer.DefFontSize:=self.currentzoom;
// Load model
self.LoadModelFromFile(Chat,Model);
if Chat.llamagguf = nil then
Chat.Free;
end;
{
Creates a new tab sheet containing a specified OpenAI custom model chat interface within the main
PageControl component.
}
procedure TForm1.AddChatGPTChat(Model:string);
var
NewTabSheet: TChatTabSheet;
Chat: TChat;
begin
// Add a new tab sheet to the page control
NewTabSheet := TChatTabSheet.Create(PageControl1);
NewTabSheet.BorderStyle:=bsNone;
NewTabSheet.PageControl:=PageControl1;
NewTabSheet.Caption:=Model;
// Allocate new ChatStruct
Chat:= TChat.Create(Model,AIT_ChatGPT,'#e2f7e8',StrToIntDef(Settings.LabeledEditMaxLen.Text,1024));
Chat.HtmlViewer := THtmlViewer.Create(NewTabSheet);
Chat.HtmlViewer.BorderStyle:=htNone;
Chat.HtmlViewer.Parent:=NewTabSheet;
Chat.HtmlViewer.ScrollBars:=ssVertical;
Chat.HtmlViewer.Align:=TAlign.alClient;
Chat.HtmlViewer.DefFontSize:=self.currentzoom;
NewTabSheet.Chat:=Chat;
PageControl1.ActivePage:=NewTabSheet;
Log('Connecting to OpenAI model '+Model+'. Remember OpenAI is not free. You will be charged for using the API. For free AI, use the Neuroengine models or local AI.');
end;
procedure TForm1.BitBtnSearchCloseClick(Sender: TObject);
var
ChatTabSheet: TChatTabSheet;
begin
self.GroupBoxSearch.Visible:=False;
ChatTabSheet:=TChatTabSheet(PageControl1.ActivePage);
if ChatTabSheet <> nil then
ChatTabSheet.Chat.HtmlViewer.CaretPos:=0;
end;
procedure TForm1.BitBtnSearchLeftClick(Sender: TObject);
var
ChatTabSheet: TChatTabSheet;
begin
// Default personality
ChatTabSheet:=TChatTabSheet(PageControl1.ActivePage);
if ChatTabSheet <> nil then
begin
ChatTabSheet.Chat.HtmlViewer.FindEx(self.EditSearch.Text,self.CheckBoxSearchCase.Checked,True);
end;
end;
procedure TForm1.BitBtnSearchRightClick(Sender: TObject);
var
ChatTabSheet: TChatTabSheet;
begin
// Default personality
ChatTabSheet:=TChatTabSheet(PageControl1.ActivePage);
if ChatTabSheet <> nil then
begin
ChatTabSheet.Chat.HtmlViewer.Find(self.EditSearch.Text,self.CheckBoxSearchCase.Checked);
end;
end;
procedure TForm1.MenuItem10Click(Sender: TObject);
begin
if Length(Settings.LabeledEditApiKey.Text)=0 then