Repository navigation
Expand file tree
/
Copy pathaibase.lua
More file actions
2636 lines (2326 loc) · 82.7 KB
/
Copy pathaibase.lua
File metadata and controls
2636 lines (2326 loc) · 82.7 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
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
--Proof of concept of implementing LLM callbacks to use with CE without the need to use Python
--Initially, this script implements the talking to and handling of a google AI type of LLM
--Feel free to add support for locally executing LLM's
--todo: add a voice to text and input the output to the AI, or if possible, enter voice as input directly ?
-- other AI systems besides google ai , websocket support
--MIT License
--https://github.com/cheat-engine/AITools
if getCEVersion()<=7.73 then _G.try=pcall end --bug bypass: earlier versions have a bugged try. pcall is the best alternative
local s=getSettings('AITOOLS',true)
local AIAccess=tonumber(s.AIAccess)
local PatreonSessionID=s.PatreonSessionID or getCEPatreonSessionID()
local AIKEY=s.AIKEY
local CustomProvider=s.CustomProvider
local CustomEndpoint=s.CustomEndpoint
if CustomProvider==nil or CustomProvider=='' then
if AIKEY and AIKEY~='' then
CustomProvider='Google Gemini'
CustomEndpoint='https://generativelanguage.googleapis.com/v1beta'
else
CustomProvider='OpenAI'
CustomEndpoint='https://api.openai.com/v1/chat/completions'
end
end
local jsonparser=require 'json'
local agreedToSendData=s.agreedToSendData or false
modelList=nil
local waitingForList={} --list of comboboxes waiting for a list of models
local pathdelim=(getOperatingSystem()==0) and [[\]] or [[/]]
local basepath=extractFilePath(getCurrentScriptPath())
if basepath==nil then
basepath=getCheatEngineDir()..'Extensions'..pathdelim..'AITools'..pathdelim
end
local modelNameToNameLookup={} --for AIAccess 2
aitools={}
aiobjects={} --todo: move to data and free objects when the chat session ends
function registerAITool(name, description, properties, required, functionToCall)
if (name==nil) or (name=='') then
error('registerAITool: name may not be nil')
end
if required==nil then
required={}
end
if properties==nil then
properties={}
end
local t={}
t.name=name
t.description=description
t.parameters={}
t.parameters.type="OBJECT"
if properties[1] then
error('Error in registerAITool for '..name..': properties must be an object, not an array')
end
t.parameters.properties=properties
t.parameters.required=required
setmetatable(t.parameters.required,{isArray=true}) --in case an empty requiredlisty is given
t.functionToCall=functionToCall
t.enabled=true
aitools[name]=t
end
function find_json_block(text)
local start_index = nil
local depth = 0
local in_string = false
local escape = false
for i = 1, #text do
local ch = text:sub(i, i)
if in_string then
if escape then
escape = false
elseif ch == "\\" then
escape = true
elseif ch == '"' then
in_string = false
end
else
if ch == '"' then
in_string = true
elseif ch == "{" then
if depth == 0 then
start_index = i
end
depth = depth + 1
elseif ch == "}" and depth > 0 then
depth = depth - 1
if depth == 0 then
local block = text:sub(start_index, i)
local remainder = text:sub(i + 1)
return block, remainder
end
end
end
end
return nil, text
end
customProviders = {
['OpenAI'] = {
protocol = 'openai',
defaultEndpoint = 'https://api.openai.com/v1/chat/completions',
defaultModel = 'gpt-4o',
modelsEndpoint = 'https://api.openai.com/v1/models',
obtainKeyUrl = 'https://platform.openai.com/api-keys',
models = {'gpt-4o', 'gpt-4o-mini', 'o3-mini', 'o1', 'gpt-4-turbo'},
requiresKey = true
},
['Anthropic'] = {
protocol = 'anthropic',
defaultEndpoint = 'https://api.anthropic.com/v1/messages',
defaultModel = 'claude-3-7-sonnet-latest',
obtainKeyUrl = 'https://console.anthropic.com/settings/keys',
models = {'claude-3-7-sonnet-latest', 'claude-3-5-sonnet-latest', 'claude-3-5-haiku-latest', 'claude-3-opus-latest'},
requiresKey = true
},
['DeepSeek'] = {
protocol = 'openai',
defaultEndpoint = 'https://api.deepseek.com/chat/completions',
defaultModel = 'deepseek-chat',
modelsEndpoint = 'https://api.deepseek.com/models',
obtainKeyUrl = 'https://platform.deepseek.com/api_keys',
models = {'deepseek-chat', 'deepseek-reasoner'},
requiresKey = true
},
['Local (Ollama)'] = {
protocol = 'openai',
defaultEndpoint = 'http://localhost:11434/v1/chat/completions',
defaultModel = 'llama3.2',
modelsEndpoint = 'http://localhost:11434/v1/models',
obtainKeyUrl = 'https://ollama.com/',
models = {'llama3.2', 'qwen2.5-coder', 'mistral', 'deepseek-r1'},
requiresKey = false
},
['Local (LM Studio)'] = {
protocol = 'openai',
defaultEndpoint = 'http://localhost:1234/v1/chat/completions',
defaultModel = 'local-model',
modelsEndpoint = 'http://localhost:1234/v1/models',
obtainKeyUrl = 'https://lmstudio.ai/',
models = {'local-model'},
requiresKey = false
},
['Google Gemini'] = {
protocol = 'gemini',
defaultEndpoint = 'https://generativelanguage.googleapis.com/v1beta',
defaultModel = 'gemini-2.5-flash',
obtainKeyUrl = 'https://aistudio.google.com/app/api-keys',
models = {'gemini-2.5-flash', 'gemini-2.5-pro', 'gemini-2.0-flash', 'gemini-1.5-pro'},
requiresKey = true
},
['Custom (OpenAI-compatible)'] = {
protocol = 'openai',
defaultEndpoint = 'http://localhost:8000/v1/chat/completions',
defaultModel = 'default',
obtainKeyUrl = nil,
models = {},
requiresKey = false
}
}
function resolveCustomProtocol(providerName, endpointUrl)
if providerName and customProviders[providerName] then
return customProviders[providerName].protocol
end
if endpointUrl then
local lowerUrl = endpointUrl:lower()
if lowerUrl:find('anthropic%.com') or lowerUrl:find('/messages') then
return 'anthropic'
elseif lowerUrl:find('googleapis%.com') or lowerUrl:find('generativelanguage') then
return 'gemini'
end
end
return 'openai'
end
function normalizeOpenAIEndpoint(url)
if not url or url == '' then return url end
local trimmed = url:gsub('^%s+', ''):gsub('%s+$', '')
if trimmed:match('/chat/completions/?$') then
if trimmed:sub(-1) == '/' then trimmed = trimmed:sub(1, -2) end
return trimmed
end
if trimmed:sub(-1) == '/' then
trimmed = trimmed:sub(1, -2)
end
if trimmed:match('/v1$') then
return trimmed .. '/chat/completions'
end
return trimmed .. '/v1/chat/completions'
end
function modelSupportsReasoning(protocol, modelname)
if not modelname or modelname == '' then
if protocol == 'gemini' then return true end
return false
end
local m = modelname:lower()
if protocol == 'gemini' then
if m:find('gemini%-1%.') or m:find('embedding') or m:find('aqa') then
return false
end
if m:find('thinking') or m:find('gemini%-2%.') or m:find('gemini%-3') or m:find('gemini%-4') or m:find('gemini%-flash') or m:find('gemini%-pro') then
return true
end
return not m:find('gemini%-1')
elseif protocol == 'anthropic' then
if m:find('claude%-3%-7') or m:find('claude%-3%.7') or m:find('claude%-4') then
return true
end
return false
elseif protocol == 'openai' then
if m:find('^o%d') or m:find('o1') or m:find('o3') or m:find('o4') or m:find('reason') or m:find('r1') or m:find('qwq') then
return true
end
return false
end
return false
end
function resolveGeminiBudget(level, modelname)
if level == nil or level == '' or level == 'Default' then
return nil
end
local m = (modelname or ''):lower()
local isProOrNextGen = m:find('pro') or m:find('gemini%-3') or m:find('gemini%-4')
local num = tonumber(level)
if num then
local maxLimit = isProOrNextGen and 65536 or 24576
return math.min(maxLimit, math.max(0, math.floor(num)))
end
if level == 'Off' then
return 0
elseif level == 'Low' then
return isProOrNextGen and 2048 or 1024
elseif level == 'Medium' then
return isProOrNextGen and 16384 or 8192
elseif level == 'High' then
return isProOrNextGen and 32768 or 24576
end
return nil
end
function resolveAnthropicBudget(level)
if level == nil or level == '' or level == 'Default' or level == 'Off' then
return nil
end
local num = tonumber(level)
if num then
return math.max(1024, math.floor(num))
end
if level == 'Low' then
return 2048
elseif level == 'Medium' then
return 8192
elseif level == 'High' then
return 16384
end
return nil
end
function resolveOpenAIReasoningEffort(level)
if level == nil or level == '' or level == 'Default' then
return nil
end
local num = tonumber(level)
if num then
if num <= 2048 then
return 'low'
elseif num <= 16384 then
return 'medium'
else
return 'high'
end
end
if level == 'Off' or level == 'Low' then
return 'low'
elseif level == 'Medium' then
return 'medium'
elseif level == 'High' then
return 'high'
end
return nil
end
local typeMapToOpenAI = {
['OBJECT'] = 'object',
['STRING'] = 'string',
['INTEGER'] = 'integer',
['NUMBER'] = 'number',
['BOOLEAN'] = 'boolean',
['ARRAY'] = 'array'
}
local typeMapToGemini = {
['object'] = 'OBJECT',
['string'] = 'STRING',
['integer'] = 'INTEGER',
['number'] = 'NUMBER',
['boolean'] = 'BOOLEAN',
['array'] = 'ARRAY'
}
function convertSchemaToOpenAI(s)
if type(s) ~= 'table' then return s end
local out = {}
for k, v in pairs(s) do
if k == 'type' and type(v) == 'string' then
out.type = typeMapToOpenAI[v:upper()] or v:lower()
elseif k == 'properties' and type(v) == 'table' then
out.properties = {}
for propName, propDef in pairs(v) do
out.properties[propName] = convertSchemaToOpenAI(propDef)
end
elseif k == 'items' and type(v) == 'table' then
out.items = convertSchemaToOpenAI(v)
elseif k == 'required' and type(v) == 'table' then
local req = {}
for _, r in ipairs(v) do
if type(r) == 'string' then
table.insert(req, r)
end
end
setmetatable(req, {isArray = true})
out.required = req
elseif k == 'enum' and type(v) == 'table' then
local en = {}
for _, ev in ipairs(v) do
table.insert(en, ev)
end
setmetatable(en, {isArray = true})
out.enum = en
else
out[k] = v
end
end
if out.properties and not out.type then
out.type = 'object'
end
return out
end
function convertSchemaToGemini(s)
if type(s) ~= 'table' then return s end
local out = {}
for k, v in pairs(s) do
if k == 'type' and type(v) == 'string' then
out.type = typeMapToGemini[v:lower()] or v:upper()
elseif k == 'properties' and type(v) == 'table' then
out.properties = {}
for propName, propDef in pairs(v) do
out.properties[propName] = convertSchemaToGemini(propDef)
end
elseif k == 'items' and type(v) == 'table' then
out.items = convertSchemaToGemini(v)
elseif k == 'required' and type(v) == 'table' then
local req = {}
for _, r in ipairs(v) do
if type(r) == 'string' then
table.insert(req, r)
end
end
setmetatable(req, {isArray = true})
out.required = req
elseif k == 'enum' and type(v) == 'table' then
local en = {}
for _, ev in ipairs(v) do
table.insert(en, ev)
end
setmetatable(en, {isArray = true})
out.enum = en
else
out[k] = v
end
end
if out.properties and not out.type then
out.type = 'OBJECT'
end
return out
end
function buildToolsForOpenAI()
local tools = {}
for name, data in pairs(aitools) do
if data.enabled then
table.insert(tools, {
type = 'function',
['function'] = {
name = name,
description = data.description,
parameters = convertSchemaToOpenAI(data.parameters)
}
})
end
end
if #tools == 0 then return nil end
return tools
end
function buildToolsForAnthropic()
local tools = {}
for name, data in pairs(aitools) do
if data.enabled then
table.insert(tools, {
name = name,
description = data.description,
input_schema = convertSchemaToOpenAI(data.parameters)
})
end
end
if #tools == 0 then return nil end
return tools
end
function buildToolsForGemini(maxtools)
local tools = { { functionDeclarations = {} } }
for name, data in pairs(aitools) do
if data.enabled then
table.insert(tools[1].functionDeclarations, {
name = name,
description = data.description,
parameters = convertSchemaToGemini(data.parameters)
})
if maxtools and #tools[1].functionDeclarations >= maxtools then
break
end
end
end
if #tools[1].functionDeclarations == 0 then return nil end
return tools
end
local retrieveModelList=nil
local fillModelList=nil
local aiRequest=nil
retrieveModelList=function(combobox)
if combobox then
combobox.clear()
end
if AIAccess==0 or AIAccess==1 then
if combobox==nil then return end
local limits=getLimits()
--return limits.models
if limits and limits.models then
for i=1,#limits.models do
combobox.items.add(limits.models[i].name)
end
else
if limits.error then
messageDialog('Failure obtaining model list:'..limits.error..'\n\r\n\rConsider becoming a patreon member or use a custom LLM. You\'ll have access to better models', mtError)
return
else
combobox.items.add('<Failed obtaining model list>')
combobox.items.add('<It\'s more than the public one>')
end
end
elseif AIAccess==2 then
local provider = CustomProvider or 'OpenAI'
local endpoint = CustomEndpoint or ''
local key = AIKEY
if combobox and combobox.Owner then
if combobox.Owner.cbCustomProvider then
provider = combobox.Owner.cbCustomProvider.Text
end
if combobox.Owner.edtCustomEndpoint then
endpoint = combobox.Owner.edtCustomEndpoint.Text
end
if combobox.Owner.edtAPIKEY then
key = combobox.Owner.edtAPIKEY.Text
end
end
local protocol = resolveCustomProtocol(provider, endpoint)
if protocol == 'gemini' then
local i=getInternet()
if key and key ~= '' then
i.Header='x-goog-api-key: '..key
end
local geminiBase = (endpoint ~= '' and endpoint) or 'https://generativelanguage.googleapis.com/v1beta'
if geminiBase:sub(-1) == '/' then geminiBase = geminiBase:sub(1, -2) end
local jsonModelList=i.getURL(geminiBase..'/models')
i.destroy()
local jml=jsonparser.decode(jsonModelList)
if jml then
if jml.error then
messageDialog('Failure obtaining model list:'..jml.error.message, mtError)
return
end
if jml.models then
modelList={}
for i=1,#jml.models do
local has_generateContent=false
if jml.models[i].supportedGenerationMethods then
for j=1,#jml.models[i].supportedGenerationMethods do
if jml.models[i].supportedGenerationMethods[j]=='generateContent' then
has_generateContent=true
break
end
end
if has_generateContent==true then
if combobox then
combobox.items.add(jml.models[i].displayName)
end
modelList[jml.models[i].displayName]=jml.models[i]
end
end
end
end
end
elseif protocol == 'openai' then
local modelsUrl = nil
if customProviders[provider] and customProviders[provider].modelsEndpoint then
modelsUrl = customProviders[provider].modelsEndpoint
elseif endpoint and endpoint ~= '' then
modelsUrl = endpoint:gsub('/chat/completions/?$', '/models')
if modelsUrl == endpoint then
modelsUrl = endpoint .. '/models'
end
end
local fetched = false
if modelsUrl then
pcall(function()
local i = getInternet()
if key and key ~= '' then
i.Header = 'Authorization: Bearer ' .. key
end
local resp = i.getURL(modelsUrl)
i.destroy()
if resp and resp:trim() ~= '' then
local data = jsonparser.decode(resp)
if data and data.data and #data.data > 0 then
modelList = {}
for idx = 1, #data.data do
local mId = data.data[idx].id
if mId and combobox then
combobox.items.add(mId)
modelList[mId] = data.data[idx]
fetched = true
end
end
end
end
end)
end
if not fetched and customProviders[provider] and customProviders[provider].models then
modelList = {}
for _, mId in ipairs(customProviders[provider].models) do
if combobox then
combobox.items.add(mId)
end
modelList[mId] = { name = mId }
end
end
elseif protocol == 'anthropic' then
if customProviders[provider] and customProviders[provider].models then
modelList = {}
for _, mId in ipairs(customProviders[provider].models) do
if combobox then
combobox.items.add(mId)
end
modelList[mId] = { name = mId }
end
end
end
end
if combobox then
local i=combobox.items.indexOf(s.DefaultModel or '')
if i~=-1 then
combobox.itemIndex=i
elseif s.DefaultModel and s.DefaultModel ~= '' then
combobox.Text = s.DefaultModel
elseif combobox.items.Count > 0 then
combobox.itemIndex = 0
end
end
end
getLimits=function()
--returns the limits of the current patreon member
local r={}
if AIAccess==2 then
r.maxtools=math.huge --infinite
return r
end
local i=getInternet()
--jsonparser
local s
if AIAccess==0 then
s=i.getURL('https://cheatengine.org/ai/limits.php')
elseif AIAccess==1 then
local i=getInternet()
i.Header='CEPATREONID:'..PatreonSessionID
s=i.getURL('https://cheatengine.org/patreon/ailimits.php')
end
i.destroy()
if s then
r=jsonparser.decode(s)
else
r.maxtools=0
end
return r
end
aiRequest=function(data, message)
local function handleError(message)
if data.self and data.self.mOutput then
data.self.mOutput.lines.add('*Error:'..message..'*\n\r')
end
if data.NotifyWhenDone then
data.NotifyWhenDone(data,'Error:'..message)
end
return nil,message
end
if not data.WaitForData and not data.NotifyWhenDone and data.FullAnswerOnly then
return nil,'The current config will result in no data'
end
_G.lastdata=data
if AIAccess~=2 then --custom provider implies you manage your own endpoint/terms
if not agreedToSendData then
synchronize(function()
agreedToSendData=messageDialog('Using the AI features involves sending your AI requests to a server where they could potentially be intercepted. Also your AI requests can be used by Google to improve their AI. Make sure not to never send personal information. Do you agree to this?',mtConfirmation,mbYes,mbNo)==mrYes
s.agreedToSendData='1'
end)
if not agreedToSendData then
return handleError('No agreement to send data')
end
end
end
if data.Internet==nil then
data.Internet=getInternet('CE AITOOLS')
end
-- Determine provider, endpoint, protocol, and key
local provider = CustomProvider or 'OpenAI'
local endpoint = CustomEndpoint or ''
local key = AIKEY
if data.self then
if data.self.cbCustomProvider then
provider = data.self.cbCustomProvider.Text
end
if data.self.edtCustomEndpoint then
endpoint = data.self.edtCustomEndpoint.Text
end
if data.self.edtAPIKEY then
key = data.self.edtAPIKEY.Text
end
end
local protocol = 'gemini'
if AIAccess == 2 then
protocol = resolveCustomProtocol(provider, endpoint)
end
data.AIAccessMode = AIAccess
data.Protocol = protocol
data.Internet.Header=[[Content-Type: application/json
Accept: text/event-stream]]
if AIAccess==1 then
if PatreonSessionID=='' then
return handleError('PatreonSessionID missing')
end
data.Internet.Header=data.Internet.Header..'\r\nCEPATREONID: '..PatreonSessionID
elseif AIAccess==2 then
local provInfo = customProviders[provider]
if provInfo and provInfo.requiresKey and (key == nil or key == '') then
return handleError('API Key missing for ' .. provider)
end
if protocol == 'openai' then
if key and key ~= '' then
data.Internet.Header = data.Internet.Header .. '\r\nAuthorization: Bearer ' .. key
end
elseif protocol == 'anthropic' then
if key and key ~= '' then
data.Internet.Header = data.Internet.Header .. '\r\nx-api-key: ' .. key
end
data.Internet.Header = data.Internet.Header .. '\r\nanthropic-version: 2023-06-01'
elseif protocol == 'gemini' then
if key and key ~= '' then
data.Internet.Header = data.Internet.Header .. '\r\nx-goog-api-key: ' .. key
end
end
end
local modelname=s.DefaultModel
if data.self and data.self.cbModelSelection then
modelname=data.self.cbModelSelection.Text
s.DefaultModel=modelname
end
if (modelname == nil or modelname == '') then
if customProviders[provider] and customProviders[provider].defaultModel then
modelname = customProviders[provider].defaultModel
else
modelname = 'gpt-4o'
end
s.DefaultModel = modelname
end
data.modelname=modelname
local thinkingLevel = 'Default'
if data.self and data.self.cbThinkingLevel then
thinkingLevel = data.self.cbThinkingLevel.Text
elseif data.ThinkingLevel then
thinkingLevel = data.ThinkingLevel
elseif s and s.ThinkingLevel then
thinkingLevel = s.ThinkingLevel
end
if thinkingLevel == nil or thinkingLevel == '' then
thinkingLevel = 'Default'
end
data.ThinkingLevel = thinkingLevel
local sysInstruction='You are a professional reverse engineer using Cheat Engine. Use tools when possible, but fall back on your internal knowledge of Cheat Engine. Do not say you can not help.'
local baseSystemText
local os=getOperatingSystem()
local arch=getSystemArchitecture()
if os==2 then --linux
baseSystemText="You're running on Linux"
elseif os==1 then --macos
baseSystemText="You're running on MacOS"
else
baseSystemText="You're running on Windows"
end
if arch==3 then
baseSystemText=baseSystemText.." (Arm 64-bit)\n"
elseif arch==2 then
baseSystemText=baseSystemText.." (Arm 32-bit)\n"
elseif arch==1 then
baseSystemText=baseSystemText.." (x86_64)\n"
else
baseSystemText=baseSystemText.." (32-bit)\n"
end
local pid=getOpenedProcessID()
if pid~=0 then
baseSystemText=baseSystemText.."Currently opened process " ..pid.." ( "..process.." )\n"
if miMonoTopMenuItem and miMonoTopMenuItem.Visible then
baseSystemText=baseSystemText.."This target uses mono/.net and CE's mono tools are available to be used\n"
end
if UEngine and type(UEngine)=='table' and UEngine.GUI and UEngine.GUI.miUnrealEngine and UEngine.GUI.miUnrealEngine.Visible then
baseSystemText=baseSystemText.."This target used Unreal Engine. CE's unreal engine tools are available\n"
if UEngine.GEngine then
baseSystemText=baseSystemText..string.format("GEngine is already known: 0x%x\n", UEngine.GEngine)
end
end
else
baseSystemText=baseSystemText.."No process has been opened yet\n"
end
local skillCatalogPrompt = (getSkillsCatalogPrompt and getSkillsCatalogPrompt()) or ''
if skillCatalogPrompt ~= '' then
baseSystemText = baseSystemText .. '\n\n' .. skillCatalogPrompt
end
if data.Extra then
baseSystemText = baseSystemText .. '\n\nAdditional Context:\n' .. data.Extra
end
local fullSystemText = sysInstruction .. '\n\n' .. baseSystemText
-- Tool execution helper
local function executeTool(name, args)
synchronize(function()
if data.self and data.self.mOutput then
if name=='getSkill' then
if args.reference then
data.self.mOutput.lines.add(' *Calling function :' .. name .. ' ('..args.skillName..', '..args.reference..')* \n\r')
else
data.self.mOutput.lines.add(' *Calling function :' .. name .. ' ('..args.skillName..')* \n\r')
end
elseif args.reason then
data.self.mOutput.lines.add(' *Calling function :' .. name .. ' ('..args.reason..')* \n\r') --Prompt you can add yourself: "When calling tools always provide a `reason` argument why you need to use this tool"
elseif args.description then
data.self.mOutput.lines.add(' *Calling function :' .. name .. ' ('..args.description..')* \n\r')
else
data.self.mOutput.lines.add(' *Calling function :' .. name .. '* \n\r')
end
end
end)
local tool = aitools[name]
if not tool then
synchronize(function()
if data.self and data.self.mOutput then
data.self.mOutput.lines.add('result: Unknown function\n\r')
end
end)
return { Error = 'Unknown function name: ' .. name }
end
if not tool.functionToCall then
synchronize(function()
if data.self and data.self.mOutput then
data.self.mOutput.lines.add('result: Invalid config\n\r')
end
end)
return { Error = 'Invalid config for ' .. name }
end
local ok, res = try(tool.functionToCall, args or {})
if not ok then
local errMsg = tostring(res)
synchronize(function()
if data.self and data.self.mOutput then
data.self.mOutput.lines.add('result error: ' .. errMsg .. '\n\r')
end
end)
return { Error = 'Tool call failed:'..errMsg }
end
return res
end
data.Error=nil
if data.allfullresponses==nil then
data.allfullresponses={}
end
local textresult=''
local thread=createThread(function(t)
data.thread=t
t.Name='AI Command Thread (' .. protocol .. ')'
if data.WaitForData then
t.freeOnTerminate(false)
end
if protocol == 'openai' then
local url = normalizeOpenAIEndpoint(endpoint ~= '' and endpoint or (customProviders[provider] and customProviders[provider].defaultEndpoint or 'https://api.openai.com/v1/chat/completions'))
data.usedurl = url
if data.history == nil then data.history = {} end
if data.history.openai_messages == nil then
data.history.openai_messages = {
{ role = 'system', content = fullSystemText },
{ role = 'user', content = message }
}
else
table.insert(data.history.openai_messages, { role = 'user', content = message })
end
local tools = buildToolsForOpenAI()
while true do
local reqBody = {
model = modelname,
messages = data.history.openai_messages,
stream = true
}
if tools then
reqBody.tools = tools
end
if modelSupportsReasoning('openai', modelname) then
local effort = resolveOpenAIReasoningEffort(thinkingLevel)
if effort then
reqBody.reasoning_effort = effort
end
end
local inputtext = jsonparser.encode(reqBody)
data.lastinputtext = inputtext
local turnStreamedText = ''
local turnAccumToolCalls = {}
local sseBuffer = ''
if data.self and (not data.FullAnswerOnly) then
data.Internet.OnReceiveData = function(sender, received)
sseBuffer = sseBuffer .. received
while true do
local nl = sseBuffer:find('\n')
if not nl then break end
local line = sseBuffer:sub(1, nl - 1):gsub('^%s+', ''):gsub('%s+$', '')
sseBuffer = sseBuffer:sub(nl + 1)
if line:sub(1, 6) == 'data: ' then
local payload = line:sub(7):gsub('^%s+', '')
if payload ~= '[DONE]' and payload ~= '' then
local ok, chunk = pcall(jsonparser.decode, payload)
if ok and chunk then
if chunk.error then
local errMsg = chunk.error.message or tostring(chunk.error)
synchronize(function()
data.self.mOutput.lines.add(' *Error:' .. errMsg .. '*\n\r')
end)
elseif chunk.choices and chunk.choices[1] then
local delta = chunk.choices[1].delta
if delta then
if delta.content and delta.content ~= '' then
turnStreamedText = turnStreamedText .. delta.content
synchronize(function()
data.self.mOutput.lines.text = data.self.mOutput.lines.text .. delta.content
data.self.mOutput.SelStart = #data.self.mOutput.lines.text
end)
end
if delta.tool_calls then
for _, tc in ipairs(delta.tool_calls) do
local idx = tc.index or 0
turnAccumToolCalls[idx] = turnAccumToolCalls[idx] or { id = '', name = '', arguments = '' }
if tc.id and tc.id ~= '' then
turnAccumToolCalls[idx].id = tc.id
end
if tc['function'] then
if tc['function'].name and tc['function'].name ~= '' then
turnAccumToolCalls[idx].name = turnAccumToolCalls[idx].name .. tc['function'].name
end
if tc['function'].arguments and tc['function'].arguments ~= '' then
turnAccumToolCalls[idx].arguments = turnAccumToolCalls[idx].arguments .. tc['function'].arguments
end
end
end
end
end
end
end
end
end
end
end
end
local result = data.Internet.postURL(url, inputtext)
if not result or result:trim() == '' then
data.Error = true
textresult = 'No response received from server'
if data.self then
synchronize(function()
data.self.mOutput.lines.add('\n\r *<server seems to be down or unreachable>*')
end)
end
break