Repository navigation
Expand file tree
/
Copy pathDelphiCon.OpenAI.KeyBindings.pas
More file actions
105 lines (84 loc) · 2.62 KB
/
Copy pathDelphiCon.OpenAI.KeyBindings.pas
File metadata and controls
105 lines (84 loc) · 2.62 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
unit DelphiCon.OpenAI.KeyBindings;
interface
uses
ToolsAPI,
VCL.Menus,
System.Classes;
type
TOpenAIKeybindings = class(TNotifierObject, IOTAKeyboardBinding)
private
procedure Bind(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult);
function SendRequestToOpenAI(const Prompt: string): string;
public
function GetBindingType: TBindingType;
function GetDisplayName: string;
function GetName: string;
procedure BindKeyboard(const BindingServices: IOTAKeyBindingServices);
end;
implementation
uses
Vcl.Dialogs,
OpenAI,
OpenAI.Completions,
System.SysUtils;
var
iKeyBindingIndex: Integer;
{ TOpenAIKeybindings }
procedure TOpenAIKeybindings.Bind(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult);
begin
if KeyCode = TextToShortCut('Ctrl+Shift+F7') then
begin
var SelectedText := Context.EditBuffer.EditBlock.Text;
var OpenAIResult := SendRequestToOpenAI(SelectedText);
var TextToInsert: TArray<string> := OpenAIResult.Split([#10, #13]);
for var Line in TextToInsert do
begin
Context.EditBuffer.EditPosition.InsertText(Line + sLineBreak);
Context.EditBuffer.EditPosition.MoveBOL;
end;
BindingResult := TKeyBindingResult.krHandled;
end;
end;
procedure TOpenAIKeybindings.BindKeyboard(const BindingServices: IOTAKeyBindingServices);
begin
BindingServices.AddKeyBinding([TextToShortCut('Ctrl+Shift+F7')], Bind, nil);
end;
function TOpenAIKeybindings.GetBindingType: TBindingType;
begin
Result := TBindingType.btPartial;
end;
function TOpenAIKeybindings.GetDisplayName: string;
begin
Result := 'DelphiCon OpenAI';
end;
function TOpenAIKeybindings.GetName: string;
begin
Result := 'DelphiConOpenAI';
end;
function TOpenAIKeybindings.SendRequestToOpenAI(const Prompt: string): string;
begin
var OpenAI := TOpenAI.Create(nil, '<your key here>');
var Completions := OpenAI.Completion.Create(
procedure(Params: TCompletionParams)
begin
Params.Prompt(Prompt);
Params.Model('text-davinci-003');
Params.MaxTokens(1000);
end);
try
for var Choice in Completions.Choices do
begin
Result := Choice.Text;
Break;
end;
finally
Completions.Free;
OpenAI.Free;
end;
end;
initialization
iKeyBindingIndex := (BorlandIDEServices As IOTAKeyboardServices).AddKeyboardBinding(TOpenAIKeybindings.Create)
finalization
if iKeyBindingIndex > 0 Then
(BorlandIDEServices As IOTAKeyboardServices).RemoveKeyboardBinding(iKeyBindingIndex);
end.