-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
ChatGPT.FrameChat.pas
1676 lines (1543 loc) · 49.5 KB
/
ChatGPT.FrameChat.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 ChatGPT.FrameChat;
interface
{$IF DEFINED(ANDROID) OR DEFINED(IOS) OR DEFINED(IOS64)}
{$DEFINE MOBILE}
{$ENDIF}
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Objects, FMX.Layouts, FMX.Memo.Types, FMX.Controls.Presentation,
FMX.Memo.Style, FMX.ScrollBox, FMX.Memo, OpenAI, OpenAI.Completions,
FMX.Edit.Style, ChatGPT.FrameMessage, ChatGPT.Classes, System.Threading,
FMX.Edit, FMX.ImgList, OpenAI.Chat, System.Generics.Collections, OpenAI.Audio,
OpenAI.Utils.ChatHistory, OpenAI.Images, ChatGPT.ChatSettings, System.JSON,
FMX.Effects, FMX.ListBox, System.Skia, FMX.Skia, ChatGPT.SoundRecorder,
FMX.InertialMovement, System.RTLConsts, OpenAI.Chat.Functions;
type
TButton = class(FMX.StdCtrls.TButton)
public
procedure SetBounds(X, Y, AWidth, AHeight: Single); override;
end;
TLabel = class(FMX.StdCtrls.TLabel)
public
procedure SetBounds(X, Y, AWidth, AHeight: Single); override;
end;
TFixedScrollCalculations = class(TScrollCalculations)
protected
procedure DoChanged; override;
end;
TVertScrollBox = class(FMX.Layouts.TVertScrollBox)
private
FViewPositionY: Single;
procedure SetViewPositionY(const Value: Single);
protected
function CreateAniCalculations: TScrollCalculations; override;
published
property ViewPositionY: Single read FViewPositionY write SetViewPositionY;
end;
TMemo = class(FMX.Memo.TMemo)
private
FViewPos: Single;
procedure SetViewPos(const Value: Single);
public
property ViewPos: Single read FViewPos write SetViewPos;
end;
TFrameChat = class(TFrame)
VertScrollBoxChat: TVertScrollBox;
LayoutSend: TLayout;
RectangleSendBG: TRectangle;
MemoQuery: TMemo;
LayoutQuery: TLayout;
RectangleMemoBG: TRectangle;
LayoutSendControls: TLayout;
LayoutTyping: TLayout;
TimerTyping: TTimer;
LayoutTypingContent: TLayout;
Layout3: TLayout;
RectangleBot: TRectangle;
Path3: TPath;
Layout4: TLayout;
RectangleIndicate: TRectangle;
LabelTyping: TLabel;
LineBorder: TLine;
LayoutWelcome: TLayout;
RectangleBG: TRectangle;
LabelWelcomeTitle: TLabel;
FlowLayoutWelcome: TFlowLayout;
LayoutExampleTitle: TLayout;
PathExaFull: TPath;
ButtonExample3: TButton;
ButtonExample2: TButton;
ButtonExample1: TButton;
LayoutCapabilitiesTitle: TLayout;
PathCapFull: TPath;
Label5: TLabel;
Label6: TLabel;
Label9: TLabel;
LayoutLimitationsTitle: TLayout;
PathLimFull: TPath;
Label8: TLabel;
Label7: TLabel;
Label10: TLabel;
Label12: TLabel;
LayoutSendCommons: TLayout;
ButtonAudio: TButton;
Path8: TPath;
ButtonSend: TButton;
PathSend: TPath;
OpenDialogAudio: TOpenDialog;
ButtonImage: TButton;
PathImage: TPath;
RectangleImageMode: TRectangle;
RectangleTypeBG: TRectangle;
LabelSendTip: TLabel;
Layout5: TLayout;
Label2: TLabel;
PathExaCompact: TPath;
Layout6: TLayout;
Label1: TLabel;
PathCapCompact: TPath;
Layout7: TLayout;
Label11: TLabel;
PathLimCompact: TPath;
LayoutChatSettings: TLayout;
ButtonSettings: TButton;
Path9: TPath;
LayoutButtom: TLayout;
ButtonRetry: TButton;
ShadowEffect1: TShadowEffect;
LayoutScrollDown: TLayout;
ButtonScrollDown: TButton;
PathAudio: TPath;
LayoutAudioRecording: TLayout;
AnimatedImageRecording: TSkAnimatedImage;
PathStopRecord: TPath;
TimerCheckRecording: TTimer;
LabelRecordingTime: TLabel;
ButtonContinue: TButton;
ShadowEffect2: TShadowEffect;
FlowLayoutActions: TFlowLayout;
ButtonExportImport: TButton;
ShadowEffect3: TShadowEffect;
Rectangle1: TRectangle;
LabelTest: TLabel;
Rectangle2: TRectangle;
Label3: TLabel;
procedure LayoutSendResize(Sender: TObject);
procedure MemoQueryChange(Sender: TObject);
procedure ButtonSendClick(Sender: TObject);
procedure TimerTypingTimer(Sender: TObject);
procedure LayoutTypingResize(Sender: TObject);
procedure MemoQueryKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure LayoutWelcomeResize(Sender: TObject);
procedure FlowLayoutWelcomeResize(Sender: TObject);
procedure ButtonExample1Click(Sender: TObject);
procedure ButtonExample2Click(Sender: TObject);
procedure ButtonExample3Click(Sender: TObject);
procedure ButtonAudioClick(Sender: TObject);
procedure ButtonImageClick(Sender: TObject);
procedure ButtonSettingsClick(Sender: TObject);
procedure ButtonRetryClick(Sender: TObject);
procedure ButtonScrollDownClick(Sender: TObject);
procedure VertScrollBoxChatViewportPositionChange(Sender: TObject; const OldViewportPosition, NewViewportPosition: TPointF; const ContentSizeChanged: Boolean);
procedure TimerCheckRecordingTimer(Sender: TObject);
procedure ButtonExample1Tap(Sender: TObject; const Point: TPointF);
procedure ButtonExample2Tap(Sender: TObject; const Point: TPointF);
procedure ButtonExample3Tap(Sender: TObject; const Point: TPointF);
procedure MemoQueryKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure MemoQueryEnter(Sender: TObject);
procedure MemoQueryViewportPositionChange(Sender: TObject; const OldViewportPosition, NewViewportPosition: TPointF; const ContentSizeChanged: Boolean);
procedure ButtonContinueClick(Sender: TObject);
procedure ButtonExportImportClick(Sender: TObject);
private
FAPI: IOpenAI;
FChatId: string;
FPool: TThreadPool;
FTitle: string;
FMode: TWindowMode;
FIsTyping: Boolean;
FBuffer: TChatHistory;
FIsImageMode: Boolean;
FTemperature: Single;
FLastRequest: TProc;
FMenuItem: TListBoxItem;
FIsFirstMessage: Boolean;
FPresencePenalty: Single;
FModel: string;
FMaxTokens: Integer;
FMaxTokensQuery: Integer;
FFrequencyPenalty: Single;
FTopP: Single;
FAudioRecord: TAudioRecord;
FRecordingStartTime: TDateTime;
FOnNeedFuncList: TOnNeedFuncList;
FUseFunctions: Boolean;
FAutoExecFuncs: Boolean;
FOnTitleChanged: TNotifyEvent;
procedure DoOnUpdateChatItems;
function NewMessage(const Text: string; Role: TMessageKind; UseBuffer: Boolean = True; IsAudio: Boolean = False): TFrameMessage;
function NewMessageImage(Role: TMessageKind; Images: TArray<string>): TFrameMessage;
procedure ClearChat;
procedure SetTyping(const Value: Boolean);
procedure SetAPI(const Value: IOpenAI);
procedure SetChatId(const Value: string);
procedure ShowError(const Text: string);
procedure AppendMessages(Response: TChat); overload;
procedure AppendMessages(Response: TImageGenerations); overload;
procedure ScrollDown(Animate: Boolean = False);
procedure SetTitle(const Value: string);
procedure SetMode(const Value: TWindowMode);
procedure AppendAudio(Response: TAudioTranscriptionObject);
procedure SetIsImageMode(const Value: Boolean);
procedure SendRequestImage;
procedure SendRequestPrompt;
procedure SetTemperature(const Value: Single);
procedure RequestPrompt;
procedure RequestImage(const Prompt: string);
procedure RequestAudio(const AudioFile: string);
procedure SetLastRequest(const Value: TProc);
procedure SetMenuItem(const Value: TListBoxItem);
procedure SetFrequencyPenalty(const Value: Single);
procedure SetMaxTokens(const Value: Integer);
procedure SetMaxTokensQuery(const Value: Integer);
procedure SetModel(const Value: string);
procedure SetPresencePenalty(const Value: Single);
procedure ChatToUp;
procedure SetTopP(const Value: Single);
procedure FOnMessageDelete(Sender: TObject);
procedure StopRecording;
procedure StartRecording;
function GenerateAudioFileName: string;
procedure FOnStartRecord(Sender: TObject);
procedure UpdateSendControls;
procedure SetOnNeedFuncList(const Value: TOnNeedFuncList);
function GetFuncs: TArray<IChatFunction>;
procedure ProcFunction(Func: TChatFunctionCall);
procedure RequestFunc(FuncResult: string);
function NewMessageFunc(const FuncName, FuncArgs: string): TFrameMessage;
procedure FOnMessageTextUpdated(Sender: TObject; const MessageId, Text: string);
procedure FOnExecuteFunc(Sender: TObject; const FuncName, FuncArgs: string; Callback: TProc<Boolean, string>);
procedure ExecuteFunc(const FuncName, FuncArgs: string; Callback: TProc<Boolean, string>);
procedure SetUseFunctions(const Value: Boolean);
procedure SetAutoExecFuncs(const Value: Boolean);
procedure SetOnTitleChanged(const Value: TNotifyEvent);
procedure SendText;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function MakeContentScreenshot: TBitmap;
function SaveAsJson: TJSONObject;
procedure LoadFromJson(JSON: TJSONObject);
property API: IOpenAI read FAPI write SetAPI;
property ChatId: string read FChatId write SetChatId;
property Title: string read FTitle write SetTitle;
property Mode: TWindowMode read FMode write SetMode;
property Temperature: Single read FTemperature write SetTemperature;
property MaxTokens: Integer read FMaxTokens write SetMaxTokens;
property MaxTokensQuery: Integer read FMaxTokensQuery write SetMaxTokensQuery;
property PresencePenalty: Single read FPresencePenalty write SetPresencePenalty;
property FrequencyPenalty: Single read FFrequencyPenalty write SetFrequencyPenalty;
property Model: string read FModel write SetModel;
property TopP: Single read FTopP write SetTopP;
property IsImageMode: Boolean read FIsImageMode write SetIsImageMode;
property LastRequest: TProc read FLastRequest write SetLastRequest;
property MenuItem: TListBoxItem read FMenuItem write SetMenuItem;
property IsFirstMessage: Boolean read FIsFirstMessage write FIsFirstMessage;
property OnNeedFuncList: TOnNeedFuncList read FOnNeedFuncList write SetOnNeedFuncList;
property UseFunctions: Boolean read FUseFunctions write SetUseFunctions;
property AutoExecFuncs: Boolean read FAutoExecFuncs write SetAutoExecFuncs;
property OnTitleChanged: TNotifyEvent read FOnTitleChanged write SetOnTitleChanged;
procedure Init;
end;
const
MAX_TOKENS = 1024;
MODEL_TOKENS_LIMIT = 4096;
ErrorHintTimeout = 'If the error is due to a timeout, you can increase the response timeout in the general program settings.';
implementation
uses
FMX.Ani, System.Math, OpenAI.API, System.IOUtils, ChatGPT.Manager,
ChatGPT.Overlay, FMX.BehaviorManager, HGM.FMX.Ani, System.Net.HttpClient,
{$IFDEF ANDROID}
ChatGPT.Android, FMX.Platform.UI.Android,
{$ENDIF}
System.DateUtils, ChatGPT.ImportExport, FMX.Text;
{$R *.fmx}
function HumanTime(Value: TTime): string;
var
H, M, S, Ms: Word;
begin
DecodeTime(Value, H, M, S, Ms);
Result := '';
if H > 0 then
Result := Result + H.ToString + ' ч. ';
if M > 0 then
Result := Result + M.ToString + ' мин. ';
if S > 0 then
Result := Result + S.ToString + ' сек. ';
if Result.IsEmpty then
Result := Result + '< 1 сек. ';
end;
function SecondsToTime(Value: Double): TTime;
begin
Result := Value / SecsPerDay;
end;
procedure TFrameChat.ShowError(const Text: string);
begin
TThread.Queue(nil,
procedure
begin
var Frame := NewMessage(Text, TMessageKind.Error, False);
Frame.IsError := True;
end);
end;
procedure TFrameChat.AppendMessages(Response: TImageGenerations);
begin
try
var Images: TArray<string>;
SetLength(Images, Length(Response.Data));
for var i := 0 to High(Response.Data) do
Images[i] := Response.Data[i].Url;
NewMessageImage(TMessageKind.Assistant, Images);
finally
Response.Free;
end;
end;
function TFrameChat.NewMessageFunc(const FuncName, FuncArgs: string): TFrameMessage;
begin
ChatToUp;
LayoutWelcome.Visible := False;
Result := TFrameMessage.Create(VertScrollBoxChat);
Result.SetMode(FMode);
Result.Position.Y := VertScrollBoxChat.ContentBounds.Height;
Result.Parent := VertScrollBoxChat;
Result.Align := TAlignLayout.MostTop;
Result.Id := '';
Result.OnDelete := FOnMessageDelete;
Result.OnTextUpdated := FOnMessageTextUpdated;
TFrameMessage(Result).MessageRole := TMessageKind.Func;
TFrameMessage(Result).FuncName := FuncName;
TFrameMessage(Result).FuncArgs := FuncArgs;
TFrameMessage(Result).FuncState := TMessageFuncState.Wait;
TFrameMessage(Result).OnFuncExecute := FOnExecuteFunc;
Result.StartAnimate;
DoOnUpdateChatItems;
if AutoExecFuncs then
TFrameMessage(Result).ExecuteFunc;
end;
function TFrameChat.NewMessageImage(Role: TMessageKind; Images: TArray<string>): TFrameMessage;
begin
ChatToUp;
LayoutWelcome.Visible := False;
Result := TFrameMessage.Create(VertScrollBoxChat);
Result.SetMode(FMode);
Result.Position.Y := VertScrollBoxChat.ContentBounds.Height;
Result.Parent := VertScrollBoxChat;
Result.Align := TAlignLayout.MostTop;
Result.Id := '';
Result.OnDelete := FOnMessageDelete;
Result.OnTextUpdated := FOnMessageTextUpdated;
TFrameMessage(Result).MessageRole := Role;
TFrameMessage(Result).Images := Images;
Result.StartAnimate;
DoOnUpdateChatItems;
end;
procedure TFrameChat.ExecuteFunc(const FuncName, FuncArgs: string; Callback: TProc<Boolean, string>);
begin
var Funcs := GetFuncs;
for var Item in Funcs do
if Item.Name = FuncName then
begin
TTask.Run(
procedure
begin
var FuncResult := '';
var ErrorText: string;
try
try
FuncResult := Item.Execute(FuncArgs);
except
on E: Exception do
begin
ErrorText := E.Message;
FuncResult := '';
end;
end;
TThread.Queue(nil,
procedure
begin
Callback(not FuncResult.IsEmpty, ErrorText);
if not FuncResult.IsEmpty then
begin
FBuffer.NewFunc(FuncName, FuncResult, TGUID.NewGuid.ToString);
RequestFunc(FuncResult);
end;
end);
finally
//
end;
end);
Exit;
end;
Callback(False, 'Function not found');
end;
procedure TFrameChat.ProcFunction(Func: TChatFunctionCall);
begin
FBuffer.NewAsistantFunc(Func.Name, Func.Arguments, TGUID.NewGuid.ToString);
var Funcs := GetFuncs;
for var Item in Funcs do
if Item.Name = Func.Name then
begin
NewMessageFunc(Func.Name, Func.Arguments);
Exit;
end;
ShowError('Function with name "' + Func.Name + '" not found');
end;
procedure TFrameChat.AppendMessages(Response: TChat);
begin
try
for var Item in Response.Choices do
if Item.FinishReason = TFinishReason.FunctionCall then
ProcFunction(Item.Message.FunctionCall)
else
NewMessage(Item.Message.Content, TMessageKind.Assistant);
finally
Response.Free;
end;
end;
procedure TFrameChat.AppendAudio(Response: TAudioTranscriptionObject);
begin
try
NewMessage(Response.Text, TMessageKind.Assistant, True, True);
finally
Response.Free;
end;
end;
function TFrameChat.SaveAsJson: TJSONObject;
begin
Result := TJSONObject.Create;
try
var JArray := TJSONArray.Create;
Result.AddPair('chat_id', FChatId);
Result.AddPair('temperature', TJSONNumber.Create(FTemperature));
Result.AddPair('title', FTitle);
Result.AddPair('items', JArray);
Result.AddPair('frequency_penalty', TJSONNumber.Create(FrequencyPenalty));
Result.AddPair('presence_penalty', TJSONNumber.Create(PresencePenalty));
Result.AddPair('max_tokens', TJSONNumber.Create(MaxTokens));
Result.AddPair('max_tokens_query', TJSONNumber.Create(MaxTokensQuery));
Result.AddPair('top_p', TJSONNumber.Create(TopP));
Result.AddPair('model', Model);
Result.AddPair('is_image_mode', IsImageMode);
Result.AddPair('draft', MemoQuery.Text);
Result.AddPair('use_functions', UseFunctions);
Result.AddPair('auto_exec_funcs', AutoExecFuncs);
for var Control in VertScrollBoxChat.Content.Controls do
if Control is TFrameMessage then
if not TFrameMessage(Control).IsError then
if not (TFrameMessage(Control).MessageRole in [TMessageKind.Error, TMessageKind.Func]) then
JArray.Add(TFrameMessage(Control).ToJsonObject);
except
//
end;
end;
procedure TFrameChat.FOnExecuteFunc(Sender: TObject; const FuncName, FuncArgs: string; Callback: TProc<Boolean, string>);
begin
ExecuteFunc(FuncName, FuncArgs, Callback);
end;
procedure TFrameChat.FOnMessageDelete(Sender: TObject);
var
Frame: TFrameMessage absolute Sender;
begin
if not (Sender is TFrameMessage) then
Exit;
FBuffer.DeleteByTag(Frame.Id);
if VertScrollBoxChat.Content.ControlsCount <= 3 then
LayoutWelcome.Visible := True;
end;
procedure TFrameChat.FOnMessageTextUpdated(Sender: TObject; const MessageId, Text: string);
var
Frame: TFrameMessage absolute Sender;
begin
if not (Sender is TFrameMessage) then
Exit;
FBuffer.SetContentByTag(MessageId, Text);
end;
function TFrameChat.GenerateAudioFileName: string;
begin
Result := TPath.Combine(Manager.AudioCacheFolder, 'audio_record' + FormatDateTime('DDMMYYYY_HHNNSS', Now) + '.wav');
end;
procedure TFrameChat.Init;
begin
//Opacity := 0;
//TAnimator.AnimateFloat(Self, 'Opacity', 1);
{$IFNDEF MOBILE}
MemoQuery.SetFocus;
{$ENDIF}
TThread.ForceQueue(nil,
procedure
begin
MemoQuery.PrepareForPaint;
MemoQueryChange(nil);
end);
end;
procedure TFrameChat.LoadFromJson(JSON: TJSONObject);
begin
var ItemCount: Integer := 0;
var LastRoleIsUser: Boolean := False;
if FChatId.IsEmpty then
FChatId := JSON.GetValue('chat_id', TGUID.NewGuid.ToString);
Title := JSON.GetValue('title', FTitle);
FTemperature := JSON.GetValue('temperature', FTemperature);
FrequencyPenalty := JSON.GetValue<Single>('frequency_penalty', FrequencyPenalty);
PresencePenalty := JSON.GetValue<Single>('presence_penalty', PresencePenalty);
TopP := JSON.GetValue<Single>('top_p', TopP);
Model := JSON.GetValue('model', Model);
MaxTokens := JSON.GetValue<Integer>('max_tokens', MaxTokens);
MaxTokensQuery := JSON.GetValue<Integer>('max_tokens_query', MaxTokensQuery);
IsImageMode := JSON.GetValue('is_image_mode', IsImageMode);
UseFunctions := JSON.GetValue('use_functions', UseFunctions);
AutoExecFuncs := JSON.GetValue('auto_exec_funcs', AutoExecFuncs);
MemoQuery.Text := JSON.GetValue('draft', MemoQuery.Text);
MemoQuery.SelStart := MemoQuery.Text.Length;
MemoQuery.SelLength := 0;
var JArray: TJSONArray;
if JSON.TryGetValue<TJSONArray>('items', JArray) then
for var JItem in JArray do
begin
var Item: TChatMessageBuild;
var IsAudio := JItem.GetValue('is_audio', False);
Item.Role := TMessageRole.FromString(JItem.GetValue('role', 'user'));
Item.Content := JItem.GetValue('content', '');
Item.Tag := JItem.GetValue('id', TGUID.NewGuid.ToString);
Item.Name := JItem.GetValue('name', '');
var Func: TFunctionCallBuild;
Func.Name := JItem.GetValue('func_name', '');
Func.Arguments := JItem.GetValue('func_args', '');
Item.FunctionCall := Func;
if not (IsAudio and (Item.Role = TMessageRole.User)) then
FBuffer.Add(Item);
var Frame := TFrameMessage.Create(VertScrollBoxChat);
Frame.Position.Y := VertScrollBoxChat.ContentBounds.Height;
VertScrollBoxChat.AddObject(Frame);
Frame.Align := TAlignLayout.MostTop;
case Item.Role of
TMessageRole.System:
Frame.MessageRole := TMessageKind.System;
TMessageRole.User:
Frame.MessageRole := TMessageKind.User;
TMessageRole.Assistant:
Frame.MessageRole := TMessageKind.Assistant;
TMessageRole.Func:
Frame.MessageRole := TMessageKind.Func;
end;
Frame.OnDelete := FOnMessageDelete;
Frame.OnTextUpdated := FOnMessageTextUpdated;
Frame.Id := Item.Tag;
Frame.Text := Item.Content;
Frame.IsAudio := IsAudio;
Frame.Images := JItem.GetValue<TArray<string>>('images', []);
Frame.FuncName := Item.FunctionCall.Name;
Frame.FuncArgs := Item.FunctionCall.Arguments;
Frame.FuncState := TMessageFuncState(JItem.GetValue('func_state', 0));
if not Frame.FuncName.IsEmpty then
Frame.OnFuncExecute := FOnExecuteFunc;
Frame.SetMode(FMode);
Frame.UpdateContentSize;
Inc(ItemCount);
end;
DoOnUpdateChatItems;
if ItemCount > 0 then
begin
LayoutWelcome.Visible := False;
IsFirstMessage := False;
ScrollDown;
if LastRoleIsUser then
LastRequest := RequestPrompt;
end;
end;
procedure TFrameChat.ScrollDown(Animate: Boolean = False);
begin
VertScrollBoxChat.RecalcSize;
if Animate then
TAnimator.AnimateFloat(VertScrollBoxChat, 'ViewPositionY', VertScrollBoxChat.ContentBounds.Height - VertScrollBoxChat.Height, 1, TAnimationType.out, TInterpolationType.Circular)
else
VertScrollBoxChat.ViewportPosition := TPointF.Create(0, VertScrollBoxChat.ContentBounds.Height - VertScrollBoxChat.Height);
end;
function TFrameChat.MakeContentScreenshot: TBitmap;
function GetMaxBitmapRect: TRectF;
var
MaxDimensionSize: Integer;
begin
MaxDimensionSize := TCanvasManager.DefaultCanvas.GetAttribute(TCanvasAttribute.MaxBitmapSize);
Result := TRectF.Create(0, 0, MaxDimensionSize, MaxDimensionSize);
end;
var
SceneScale: Single;
BitmapRect: TRectF;
begin
if Scene <> nil then
SceneScale := Scene.GetSceneScale
else
SceneScale := 1;
// TBitmap has limitation of size. It's a max texture size. If we takes screenshot of control, which exceeds this
// limitation, we get "Bitmap size to big" exception. So we normalize size for avoiding it.
BitmapRect := TRectF.Create(0, 0, VertScrollBoxChat.Content.ScrollBox.ContentBounds.Width * SceneScale, VertScrollBoxChat.Content.ScrollBox.ContentBounds.Height * SceneScale);
BitmapRect := BitmapRect.PlaceInto(GetMaxBitmapRect);
Result := TBitmap.Create(Round(BitmapRect.Width), Round(BitmapRect.Height));
Result.BitmapScale := SceneScale;
Result.Clear(0);
if Result.Canvas.BeginScene then
try
VertScrollBoxChat.Content.PaintTo(Result.Canvas, TRectF.Create(0, 0, Result.Width / SceneScale, Result.Height / SceneScale));
finally
Result.Canvas.EndScene;
end;
end;
procedure TFrameChat.ButtonSettingsClick(Sender: TObject);
begin
TFrameChatSettings.Execute(Self,
procedure(Frame: TFrameChatSettings)
begin
Frame.Mode := FMode;
Frame.TrackBarTemp.Value := Temperature * 10;
Frame.TrackBarPP.Value := PresencePenalty * 10;
Frame.TrackBarFP.Value := FrequencyPenalty * 10;
if MaxTokens <> 0 then
Frame.EditMaxTokens.Text := MaxTokens.ToString
else
Frame.EditMaxTokens.Text := '';
if MaxTokensQuery <> 0 then
Frame.EditQueryMaxToken.Text := MaxTokensQuery.ToString
else
Frame.EditQueryMaxToken.Text := '';
Frame.ComboEditModel.Text := Model;
Frame.TrackBarTopP.Value := TopP * 10;
Frame.SwitchUseFunctions.IsChecked := UseFunctions;
Frame.SwitchAutoExecFuncs.IsChecked := AutoExecFuncs;
end,
procedure(Frame: TFrameChatSettings; Success: Boolean)
begin
MemoQuery.SetFocus;
if not Success then
Exit;
Temperature := Frame.TrackBarTemp.Value / 10;
PresencePenalty := Frame.TrackBarPP.Value / 10;
FrequencyPenalty := Frame.TrackBarFP.Value / 10;
MaxTokens := StrToIntDef(Frame.EditMaxTokens.Text, 0);
MaxTokensQuery := StrToIntDef(Frame.EditQueryMaxToken.Text, 0);
TopP := Frame.TrackBarTopP.Value / 10;
Model := Frame.ComboEditModel.Text;
UseFunctions := Frame.SwitchUseFunctions.IsChecked;
AutoExecFuncs := Frame.SwitchAutoExecFuncs.IsChecked;
end);
end;
procedure TFrameChat.ButtonAudioClick(Sender: TObject);
begin
if FIsTyping then
Exit;
{$IFNDEF ANDROID}
if not OpenDialogAudio.Execute then
Exit;
var AudioFile := OpenDialogAudio.FileName;
//MemoQuery.Text := '';
NewMessage(TPath.GetFileName(AudioFile), TMessageKind.User, False, True);
RequestAudio(AudioFile);
{$ELSE}
try
OpenFileDialog('*/*',
procedure(FilePath: string)
begin
//MemoQuery.Text := '';
NewMessage(TPath.GetFileName(FilePath), TMessageKind.User, False, True);
RequestAudio(FilePath);
end);
except
on E: Exception do
ShowError(E.Message);
end;
{$ENDIF}
end;
procedure TFrameChat.ButtonContinueClick(Sender: TObject);
begin
RequestPrompt;
end;
procedure TFrameChat.RequestAudio(const AudioFile: string);
begin
SetTyping(True);
ScrollDown;
LastRequest := nil;
TTask.Run(
procedure
begin
try
var Audio := API.Audio.CreateTranscription(
procedure(Params: TAudioTranscription)
begin
Params.&File(AudioFile);
Params.Temperature(Temperature / 2);
Params.Language('ru');
end);
TThread.Queue(nil,
procedure
begin
AppendAudio(Audio);
end);
except
on E: OpenAIException do
begin
ShowError(E.Message);
LastRequest :=
procedure
begin
RequestAudio(AudioFile);
end;
end;
on E: Exception do
begin
ShowError(E.Message);
LastRequest :=
procedure
begin
RequestAudio(AudioFile);
end;
end;
end;
TThread.Queue(nil,
procedure
begin
SetTyping(False);
end);
end, FPool);
end;
procedure TFrameChat.ButtonExample1Click(Sender: TObject);
begin
if MemoQuery.Text.IsEmpty then
MemoQuery.Text := 'Explain quantum computing in simple terms';
end;
procedure TFrameChat.ButtonExample1Tap(Sender: TObject; const Point: TPointF);
begin
ButtonExample1Click(Sender);
end;
procedure TFrameChat.ButtonExample2Click(Sender: TObject);
begin
if MemoQuery.Text.IsEmpty then
MemoQuery.Text := 'Got any creative ideas for a 10 year old’s birthday?';
end;
procedure TFrameChat.ButtonExample2Tap(Sender: TObject; const Point: TPointF);
begin
ButtonExample2Click(Sender);
end;
procedure TFrameChat.ButtonExample3Click(Sender: TObject);
begin
if MemoQuery.Text.IsEmpty then
MemoQuery.Text := 'How do I make an HTTP request in Javascript?';
end;
procedure TFrameChat.ButtonExample3Tap(Sender: TObject; const Point: TPointF);
begin
ButtonExample3Click(Sender);
end;
procedure TFrameChat.ButtonExportImportClick(Sender: TObject);
begin
TFrameImportExport.Execute(Self,
procedure(Frame: TFrameImportExport)
begin
Frame.Mode := FMode;
end,
procedure(Frame: TFrameImportExport; Success: Boolean)
begin
MemoQuery.SetFocus;
if not Success then
Exit;
if Frame.RadioButtonExport.IsChecked then
begin
if Frame.EditExport.Text.EndsWith('.json') then
begin
var JSON := SaveAsJson;
if Assigned(JSON) then
try
TFile.WriteAllText(Frame.EditExport.Text, JSON.ToJSON, TEncoding.UTF8);
finally
JSON.Free;
end;
end
else
begin
var Stream := TFile.Create(Frame.EditExport.Text);
try
for var Control in VertScrollBoxChat.Content.Controls do
if Control is TFrameMessage then
if not TFrameMessage(Control).IsError then
begin
var Buff := TEncoding.UTF8.GetBytes(TFrameMessage(Control).MessageRole.ToString + #13#10 + TFrameMessage(Control).Text + #13#10 + #13#10 + #13#10);
Stream.WriteBuffer(Buff, Length(Buff));
end;
finally
Stream.Free;
end;
end;
end
else
begin
var JSON := TJSONObject.ParseJSONValue(TFile.ReadAllText(Frame.EditImport.Text, TEncoding.UTF8));
if Assigned(JSON) then
try
LoadFromJson(JSON as TJSONObject);
finally
JSON.Free;
end;
end;
end);
end;
procedure TFrameChat.ButtonImageClick(Sender: TObject);
begin
IsImageMode := not IsImageMode;
end;
procedure TFrameChat.ButtonRetryClick(Sender: TObject);
begin
if Assigned(FLastRequest) then
FLastRequest;
end;
procedure TFrameChat.SendRequestImage;
begin
if FIsTyping then
Exit;
var Prompt := MemoQuery.Text;
if Prompt.IsEmpty then
Exit;
MemoQuery.Text := '';
NewMessage(Prompt, TMessageKind.User, False);
RequestImage(Prompt);
end;
procedure TFrameChat.RequestImage(const Prompt: string);
begin
SetTyping(True);
ScrollDown;
LastRequest := nil;
TTask.Run(
procedure
begin
try
var Images := API.Image.Create(
procedure(Params: TImageCreateParams)
begin
Params.Prompt(Prompt);
Params.ResponseFormat(TImageResponseFormat.Url);
Params.N(4);
Params.Model('');
Params.Size(TImageSize.s1024x1024);
Params.User(FChatId);
end);
TThread.Queue(nil,
procedure
begin
AppendMessages(Images);
end);
except
on E: OpenAIException do
begin
ShowError(E.Message);
LastRequest :=
procedure
begin
RequestImage(Prompt);
end;
end;
on E: Exception do
begin
ShowError(E.Message);
LastRequest :=
procedure
begin
RequestImage(Prompt);
end;
end;
end;
TThread.Queue(nil,
procedure
begin
SetTyping(False);
end);
end, FPool);
end;
procedure TFrameChat.SendRequestPrompt;
begin
if FIsTyping then
Exit;
var Prompt := MemoQuery.Text.Trim([' ', #13, #10]);
if Prompt.IsEmpty then
Exit;
MemoQuery.Text := '';
NewMessage(Prompt, TMessageKind.User);
if (not Prompt.StartsWith('/system ')) and (not Prompt.StartsWith('/assistant ')) and (not Prompt.StartsWith('/user ')) then
RequestPrompt;
end;
function TFrameChat.GetFuncs: TArray<IChatFunction>;
begin
if Assigned(FOnNeedFuncList) and FUseFunctions then
FOnNeedFuncList(Self, Result)
else
Result := [];
end;
function CreateTools(Funcs: TArray<IChatFunction>): TArray<TChatToolParam>;
begin
for var Item in Funcs do
Result := Result + [TChatToolFunctionParam.Create(Item)];
end;
procedure TFrameChat.RequestFunc(FuncResult: string);
begin
SetTyping(True);
ScrollDown;
LastRequest := nil;
TTask.Run(
procedure
begin
try
var Funcs := GetFuncs;
var Completions := API.Chat.Create(
procedure(Params: TChatParams)
begin
if not Model.IsEmpty then
Params.Model(Model);
if PresencePenalty <> 0 then
Params.PresencePenalty(PresencePenalty);
if FrequencyPenalty <> 0 then
Params.FrequencyPenalty(FrequencyPenalty);
Params.Messages(FBuffer.ToArray);
if FBuffer.MaxTokensForQuery <> 0 then
Params.MaxTokens(FBuffer.MaxTokensForQuery);
Params.Temperature(Temperature);
if Length(Funcs) > 0 then
begin
Params.Tools(CreateTools(Funcs));
Params.ToolChoice(TChatToolChoiceParam.Auto);
end;
Params.User(FChatId);
end);
TThread.Queue(nil,
procedure
begin
AppendMessages(Completions);
end);
except
on E: OpenAIException do
begin
ShowError(E.Message);
LastRequest :=
procedure
begin
RequestFunc(FuncResult);
end;
end;
on E: Exception do
begin
ShowError(E.Message);
LastRequest :=
procedure
begin
RequestFunc(FuncResult);
end;
end;