-
Notifications
You must be signed in to change notification settings - Fork 29
/
llm.py
1927 lines (1822 loc) · 84.4 KB
/
llm.py
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
import base64
import datetime
import gc
import glob
import hashlib
import importlib
import io
import json
import os
import re
import sys
import time
import traceback
import numpy as np
import openai
import requests
import torch
from PIL import Image
from transformers import (
AutoModel,
AutoModelForCausalLM,
AutoTokenizer,
GenerationConfig,
)
if torch.cuda.is_available():
from transformers import BitsAndBytesConfig
from torchvision.transforms import ToPILImage
from .config import config_key, config_path, current_dir_path, load_api_keys
from .tools.api_tool import api_tool, use_api_tool,api_function,parameter_function,parameter_combine, parameter_combine_plus,list_append,list_append_plus,list_extend,list_extend_plus
from .tools.arxiv import arxiv_tool, get_arxiv
from .tools.check_web import check_web, check_web_tool
from .tools.classify_function import classify_function, classify_function_plus
from .tools.classify_persona import classify_persona, classify_persona_plus
from .tools.CosyVoice import CosyVoice
from .tools.custom_persona import custom_persona
from .tools.dialog import end_dialog, start_dialog
from .tools.dingding import Dingding, Dingding_tool, send_dingding
from .tools.end_work import end_workflow
from .tools.excel import image_iterator, load_excel
from .tools.feishu import feishu, feishu_tool, send_feishu
from .tools.file_combine import file_combine, file_combine_plus
from .tools.get_time import get_time, time_tool
from .tools.get_weather import (
accuweather_tool,
get_accuweather,
get_weather,
weather_tool,
)
from .tools.git_tool import github_tool, search_github_repositories
from .tools.image import CLIPTextEncode_party, KSampler_party, VAEDecode_party
from .tools.interpreter import interpreter, interpreter_tool
from .tools.keyword import keyword_tool, load_keyword, search_keyword
from .tools.KG import (
Delete_entities,
Delete_relationships,
Inquire_entities,
Inquire_entity_list,
Inquire_entity_relationships,
Inquire_relationships,
KG_json_toolkit_developer,
KG_json_toolkit_user,
Modify_entities,
Modify_relationships,
New_entities,
New_relationships,
)
from .tools.KG_csv import (
Delete_triple,
Inquire_triple,
KG_csv_toolkit_developer,
KG_csv_toolkit_user,
New_triple,
)
from .tools.KG_neo4j import (
Delete_entities_neo4j,
Delete_relationships_neo4j,
Inquire_entities_neo4j,
Inquire_entity_list_neo4j,
Inquire_entity_relationships_neo4j,
Inquire_relationships_neo4j,
KG_neo_toolkit_developer,
KG_neo_toolkit_user,
Modify_entities_neo4j,
Modify_relationships_neo4j,
New_entities_neo4j,
New_relationships_neo4j,
)
from .tools.load_ebd import data_base, ebd_tool, load_embeddings
from .tools.load_file import load_file, load_file_folder, load_url, start_workflow
from .tools.load_model_name import load_name
from .tools.load_persona import load_persona
from .tools.logic import get_string, replace_string, string_logic, substring
from .tools.new_interpreter import new_interpreter, new_interpreter_tool
from .tools.omost import omost_decode, omost_setting
from .tools.search_web import bing_tool, google_tool, search_web, search_web_bing,google_loader,bing_loader
from .tools.show_text import About_us, show_text_party
from .tools.story import read_story_json, story_json_tool
from .tools.text_iterator import text_iterator
from .tools.tool_combine import tool_combine, tool_combine_plus
from .tools.translate_persona import translate_persona
from .tools.tts import openai_tts, play_audio
from .tools.wechat import send_wechat, work_wechat, work_wechat_tool
from .tools.whisper import listen_audio, openai_whisper
from .tools.wikipedia import get_wikipedia, load_wikipedia, wikipedia_tool
from .tools.workflow import work_flow, workflow_tool, workflow_transfer
from .tools.clear_model import clear_model
_TOOL_HOOKS = [
"get_time",
"get_weather",
"search_web",
"search_web_bing",
"check_web",
"interpreter",
"data_base",
"another_llm",
"new_interpreter",
"use_api_tool",
"get_accuweather",
"get_wikipedia",
"get_arxiv",
"work_flow",
"search_github_repositories",
"send_wechat",
"send_dingding",
"send_feishu",
"search_keyword",
"read_story_json",
"Inquire_entities",
"New_entities",
"Modify_entities",
"Delete_entities",
"Inquire_relationships",
"New_relationships",
"Modify_relationships",
"Delete_relationships",
"Inquire_triple",
"New_triple",
"Delete_triple",
"Inquire_entity_relationships",
"Inquire_entity_list",
"Inquire_entities_neo4j",
"New_entities_neo4j",
"Modify_entities_neo4j",
"Delete_entities_neo4j",
"Inquire_relationships_neo4j",
"New_relationships_neo4j",
"Modify_relationships_neo4j",
"Delete_relationships_neo4j",
"Inquire_entity_relationships_neo4j",
"Inquire_entity_list_neo4j",
]
instances = []
image_buffer = []
def another_llm(id, type, question):
print(id, type, question)
global instances
if type == "api":
try:
llm = next((instance for instance in instances if str(instance.id).strip() == str(id).strip()), None)
except:
print("找不到对应的智能助手")
return "找不到对应的智能助手"
if llm is None:
print("找不到对应的智能助手")
return "找不到对应的智能助手"
(
main_brain,
system_prompt,
model,
temperature,
is_memory,
is_tools_in_sys_prompt,
is_locked,
max_length,
system_prompt_input,
user_prompt_input,
tools,
file_content,
images,
imgbb_api_key,
conversation_rounds,
historical_record,
) = llm.list
res, _, _, _ = llm.chatbot(
question,
main_brain,
system_prompt,
model,
temperature,
is_memory,
is_tools_in_sys_prompt,
is_locked,
max_length,
system_prompt_input,
user_prompt_input,
tools,
file_content,
images,
imgbb_api_key,
conversation_rounds,
historical_record,
)
elif type == "local":
try:
llm = next((instance for instance in instances if str(instance.id).strip() == str(id).strip()), None)
except:
print("找不到对应的智能助手")
return "找不到对应的智能助手"
if llm is None:
print("找不到对应的智能助手")
return "找不到对应的智能助手"
(
main_brain,
system_prompt,
model_type,
model,
tokenizer,
temperature,
max_length,
is_memory,
is_locked,
system_prompt_input,
user_prompt_input,
tools,
file_content,
image,
conversation_rounds,
historical_record,
) = llm.list
res, _, _, _ = llm.chatbot(
question,
main_brain,
system_prompt,
model_type,
model,
tokenizer,
temperature,
max_length,
is_memory,
is_locked,
system_prompt_input,
user_prompt_input,
tools,
file_content,
image,
conversation_rounds,
historical_record,
)
else:
return "type参数错误,请使用api或local"
print(res)
return "你调用的智能助手的问答是:" + res + "\n请根据以上回答,回答用户的问题。"
llm_tools_list = []
llm_tools = [
{
"type": "function",
"function": {
"name": "another_llm",
"description": "使用llm_tools可以调用其他的智能助手解决你的问题。请根据以下列表中的system_prompt选择你需要的智能助手:"
+ json.dumps(llm_tools_list, ensure_ascii=False, indent=4),
"parameters": {
"type": "object",
"properties": {
"id": {"type": "string", "description": "智能助手的id"},
"type": {"type": "string", "description": "智能助手的类型,目前支持api和local两种类型。"},
"question": {"type": "string", "description": "问题描述,代表你想要解决的问题。"},
},
"required": ["id", "type", "question"],
},
},
}
]
def dispatch_tool(tool_name: str, tool_params: dict) -> str:
if "multi_tool_use." in tool_name:
tool_name = tool_name.replace("multi_tool_use.", "")
if tool_name not in _TOOL_HOOKS:
return f"Tool `{tool_name}` not found. Please use a provided tool."
tool_call = globals().get(tool_name)
try:
ret_out = tool_call(**tool_params)
if tool_name == "work_flow":
ret = ret_out[0]
image_buffer = ret_out[1]
if ret == "" or ret is None:
ret = "图片已生成。"
else:
ret = ret_out
except:
ret = traceback.format_exc()
return str(ret)
class Chat:
def __init__(self, model_name, apikey, baseurl) -> None:
self.model_name = model_name
self.apikey = apikey
self.baseurl = baseurl
def send(self, user_prompt, temperature, max_length, history, tools=None):
try:
openai.api_key = self.apikey
openai.base_url = self.baseurl
new_message = {"role": "user", "content": user_prompt}
history.append(new_message)
print(history)
if tools is not None:
response = openai.chat.completions.create(
model=self.model_name,
messages=history,
temperature=temperature,
tools=tools,
max_tokens=max_length,
)
while response.choices[0].message.tool_calls:
assistant_message = response.choices[0].message
response_content = assistant_message.tool_calls[0].function
print("正在调用" + response_content.name + "工具")
print(response_content.arguments)
results = dispatch_tool(response_content.name, json.loads(response_content.arguments))
print(results)
history.append(
{
"tool_calls": [
{
"id": assistant_message.tool_calls[0].id,
"function": {
"arguments": response_content.arguments,
"name": response_content.name,
},
"type": assistant_message.tool_calls[0].type,
}
],
"role": "assistant",
"content": str(response_content),
}
)
history.append(
{
"role": "tool",
"tool_call_id": assistant_message.tool_calls[0].id,
"name": response_content.name,
"content": results,
}
)
try:
response = openai.chat.completions.create(
model=self.model_name,
messages=history,
tools=tools,
temperature=temperature,
max_tokens=max_length,
)
print(response)
except Exception as e:
print("tools calling失败,尝试使用function calling" + str(e))
# 删除history最后两个元素
history.pop()
history.pop()
history.append(
{
"role": "assistant",
"content": str(response_content),
"function_call": {
"name": response_content.name,
"arguments": response_content.arguments,
},
}
)
history.append({"role": "function", "name": response_content.name, "content": results})
response = openai.chat.completions.create(
model=self.model_name,
messages=history,
tools=tools,
temperature=temperature,
max_tokens=max_length,
)
print(response)
while response.choices[0].message.function_call:
assistant_message = response.choices[0].message
function_call = assistant_message.function_call
function_name = function_call.name
function_arguments = json.loads(function_call.arguments)
print("正在调用" + function_name + "工具")
results = dispatch_tool(function_name, function_arguments)
print(results)
history.append(
{
"role": "assistant",
"content": str(function_call),
"function_call": {"name": function_name, "arguments": function_arguments},
}
)
history.append({"role": "function", "name": function_name, "content": results})
response = openai.chat.completions.create(
model=self.model_name,
messages=history,
tools=tools,
temperature=temperature,
max_tokens=max_length,
)
response_content = response.choices[0].message.content
print(response)
# 正则表达式匹配
pattern = r'\{\s*"tool":\s*"(.*?)",\s*"parameters":\s*\{(.*?)\}\s*\}'
while re.search(pattern, response_content, re.DOTALL) != None:
match = re.search(pattern, response_content, re.DOTALL)
tool = match.group(1)
parameters = match.group(2)
json_str = '{"tool": "' + tool + '", "parameters": {' + parameters + "}}"
print("正在调用" + tool + "工具")
parameters = json.loads("{" + parameters + "}")
results = dispatch_tool(tool, parameters)
print(results)
history.append({"role": "assistant", "content": json_str})
history.append(
{
"role": "user",
"content": "调用"
+ tool
+ "工具返回的结果为:"
+ results
+ "。请根据工具返回的结果继续回答我之前提出的问题。",
}
)
response = openai.chat.completions.create(
model=self.model_name, messages=history, temperature=temperature, max_tokens=max_length
)
response_content = response.choices[0].message.content
else:
response = openai.chat.completions.create(
model=self.model_name,
messages=history,
temperature=temperature,
max_tokens=max_length,
)
response_content = response.choices[0].message.content
history.append({"role": "assistant", "content": response_content})
except Exception as ex:
response_content = str(ex)
return response_content, history
class LLM_api_loader:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model_name": ("STRING", {"default": "gpt-3.5-turbo-1106"}),
},
"optional": {
"base_url": (
"STRING",
{
"default": "https://api.openai.com/v1/",
},
),
"api_key": (
"STRING",
{
"default": "sk-XXXXX",
},
),
},
}
RETURN_TYPES = ("CUSTOM",)
RETURN_NAMES = ("model",)
FUNCTION = "chatbot"
# OUTPUT_NODE = False
CATEGORY = "大模型派对(llm_party)/加载器(loader)"
def chatbot(self, model_name, base_url=None, api_key=None):
api_keys = load_api_keys(config_path)
if api_key != "":
openai.api_key = api_key
elif model_name in config_key:
api_keys = config_key[model_name]
openai.api_key = api_keys.get("api_key")
elif api_keys.get("openai_api_key") != "":
openai.api_key = api_keys.get("openai_api_key")
else:
openai.api_key = os.environ.get("OPENAI_API_KEY")
if base_url != "":
openai.base_url = base_url
elif model_name in config_key:
api_keys = config_key[model_name]
openai.base_url = api_keys.get("base_url")
elif api_keys.get("base_url") != "":
openai.base_url = api_keys.get("base_url")
else:
openai.base_url = os.environ.get("OPENAI_API_BASE")
if openai.api_key == "":
return ("请输入API_KEY",)
if openai.base_url != "":
if openai.base_url[-1] != "/":
openai.base_url = openai.base_url + "/"
chat = Chat(model_name, openai.api_key, openai.base_url)
return (chat,)
class LLM:
original_IS_CHANGED = None
def __init__(self):
current_time = datetime.datetime.now()
# 以时间戳作为ID,字符串格式 XX年XX月XX日XX时XX分XX秒
self.id = current_time.strftime("%Y_%m_%d_%H_%M_%S")
global instances
instances.append(self)
# 构建prompt.json的绝对路径,如果temp文件夹不存在就创建
current_dir_path = os.path.dirname(os.path.abspath(__file__))
os.makedirs(os.path.join(current_dir_path, "temp"), exist_ok=True)
self.prompt_path = os.path.join(current_dir_path, "temp", str(self.id) + ".json")
# 如果文件不存在,创建prompt.json文件,存在就覆盖文件
if not os.path.exists(self.prompt_path):
with open(self.prompt_path, "w", encoding="utf-8") as f:
json.dump(
[{"role": "system", "content": "你是一个强大的人工智能助手。"}], f, indent=4, ensure_ascii=False
)
self.tool_data = {"id": self.id, "system_prompt": "", "type": "api"}
self.list = []
self.added_to_list = False
self.is_locked = "disable"
@classmethod
def INPUT_TYPES(s):
temp_path = os.path.join(current_dir_path, "temp")
full_paths = [os.path.join(temp_path, f) for f in os.listdir(temp_path)]
full_paths.sort(key=os.path.getmtime, reverse=True)
paths = [os.path.basename(f) for f in full_paths]
paths.insert(0, "")
return {
"required": {
"system_prompt": ("STRING", {"multiline": True, "default": "你一个强大的人工智能助手。"}),
"user_prompt": (
"STRING",
{
"multiline": True,
"default": "你好",
},
),
"model": ("CUSTOM", {}),
"temperature": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 1.0, "step": 0.1}),
"is_memory": (["enable", "disable"], {"default": "enable"}),
"is_tools_in_sys_prompt": (["enable", "disable"], {"default": "disable"}),
"is_locked": (["enable", "disable"], {"default": "disable"}),
"main_brain": (["enable", "disable"], {"default": "enable"}),
"max_length": ("FLOAT", {"default": 1920, "min": 256, "max": 128000, "step": 128}),
},
"optional": {
"system_prompt_input": ("STRING", {"forceInput": True}),
"user_prompt_input": ("STRING", {"forceInput": True}),
"tools": ("STRING", {"forceInput": True}),
"file_content": ("STRING", {"forceInput": True}),
"images": ("IMAGE", {"forceInput": True}),
"imgbb_api_key": (
"STRING",
{
"default": "",
},
),
"conversation_rounds": ("INT", {"default": 100, "min": 1, "max": 10000}),
"historical_record": (paths, {"default": ""}),
},
}
RETURN_TYPES = (
"STRING",
"STRING",
"STRING",
"IMAGE",
)
RETURN_NAMES = (
"assistant_response",
"history",
"tool",
"image",
)
FUNCTION = "chatbot"
# OUTPUT_NODE = False
CATEGORY = "大模型派对(llm_party)/模型链(model_chain)"
def chatbot(
self,
user_prompt,
main_brain,
system_prompt,
model,
temperature,
is_memory,
is_tools_in_sys_prompt,
is_locked,
max_length,
system_prompt_input="",
user_prompt_input="",
tools=None,
file_content=None,
images=None,
imgbb_api_key=None,
conversation_rounds=100,
historical_record="",
):
self.list = [
main_brain,
system_prompt,
model,
temperature,
is_memory,
is_tools_in_sys_prompt,
is_locked,
max_length,
system_prompt_input,
user_prompt_input,
tools,
file_content,
images,
imgbb_api_key,
conversation_rounds,
historical_record,
]
if user_prompt is None:
user_prompt = user_prompt_input
else:
user_prompt = user_prompt + user_prompt_input
if historical_record != "":
temp_path = os.path.join(current_dir_path, "temp")
self.prompt_path = os.path.join(temp_path, historical_record)
self.tool_data["system_prompt"] = system_prompt
if system_prompt_input is not None and system_prompt is not None:
system_prompt = system_prompt + system_prompt_input
elif system_prompt is None:
system_prompt = system_prompt_input
global llm_tools_list, llm_tools
if main_brain == "disable":
if self.added_to_list == False:
llm_tools_list.append(self.tool_data)
self.added_to_list = True
self.is_locked = is_locked
if LLM.original_IS_CHANGED is None:
# 保存原始的IS_CHANGED方法的引用
LLM.original_IS_CHANGED = LLM.IS_CHANGED
if self.is_locked == "disable":
setattr(LLM, "IS_CHANGED", LLM.original_IS_CHANGED)
else:
# 如果方法存在,则删除
if hasattr(LLM, "IS_CHANGED"):
delattr(LLM, "IS_CHANGED")
llm_tools = [
{
"type": "function",
"function": {
"name": "another_llm",
"description": "使用llm_tools可以调用其他的智能助手解决你的问题。请根据以下列表中的system_prompt选择你需要的智能助手:"
+ json.dumps(llm_tools_list, ensure_ascii=False, indent=4),
"parameters": {
"type": "object",
"properties": {
"id": {"type": "string", "description": "智能助手的id"},
"type": {"type": "string", "description": "智能助手的类型,目前支持api和local两种类型。"},
"question": {"type": "string", "description": "问题描述,代表你想要解决的问题。"},
},
"required": ["id", "type", "question"],
},
},
}
]
llm_tools_json = json.dumps(llm_tools, ensure_ascii=False, indent=4)
if user_prompt is None or user_prompt.strip() == "":
with open(self.prompt_path, "r", encoding="utf-8") as f:
history = json.load(f)
return (
"",
str(history),
llm_tools_json,
None,
)
else:
try:
if is_memory == "disable":
with open(self.prompt_path, "w", encoding="utf-8") as f:
json.dump([{"role": "system", "content": system_prompt}], f, indent=4, ensure_ascii=False)
api_keys = load_api_keys(config_path)
with open(self.prompt_path, "r", encoding="utf-8") as f:
history = json.load(f)
history_temp = [history[0]]
elements_to_keep = 2 * conversation_rounds
if elements_to_keep < len(history) - 1:
history_temp += history[-elements_to_keep:]
history_copy = history[1:-elements_to_keep]
else:
if len(history) > 1:
history_temp += history[1:]
history_copy = []
if len(history_temp) > 1:
if history_temp[1]["role"] == "tool":
history_temp.insert(1, history[-elements_to_keep - 1])
if -elements_to_keep - 1 > 1:
history_copy = history[1 : -elements_to_keep - 1]
else:
history_copy = []
history = history_temp
for message in history:
if message["role"] == "system":
message["content"] = system_prompt
if is_tools_in_sys_prompt == "enable":
tools_list = []
GPT_INSTRUCTION = ""
if tools is not None:
tools_dis = json.loads(tools)
for tool_dis in tools_dis:
tools_list.append(tool_dis["function"])
tools_instructions = ""
tools_instruction_list = []
for tool in tools_list:
tools_instruction_list.append(tool["name"])
tools_instructions += (
str(tool["name"])
+ ":"
+ "Call this tool to interact with the "
+ str(tool["name"])
+ " API. What is the "
+ str(tool["name"])
+ " API useful for? "
+ str(tool["description"])
+ ". Parameters:"
+ str(tool["parameters"])
+ "Required parameters:"
+ str(tool["parameters"]["required"])
+ "\n"
)
REUTRN_FORMAT = '{"tool": "tool name", "parameters": {"parameter name": "parameter value"}}'
TOOL_EAXMPLE = 'You will receive a JSON string containing a list of callable tools. Please parse this JSON string and return a JSON object containing the tool name and tool parameters. Here is an example of the tool list:\n\n{"tools": [{"name": "plus_one", "description": "Add one to a number", "parameters": {"type": "object","properties": {"number": {"type": "string","description": "The number that needs to be changed, for example: 1","default": "1",}},"required": ["number"]}},{"name": "minus_one", "description": "Minus one to a number", "parameters": {"type": "object","properties": {"number": {"type": "string","description": "The number that needs to be changed, for example: 1","default": "1",}},"required": ["number"]}}]}\n\nBased on this tool list, generate a JSON object to call a tool. For example, if you need to add one to number 77, return:\n\n{"tool": "plus_one", "parameters": {"number": "77"}}\n\nPlease note that the above is just an example and does not mean that the plus_one and minus_one tools are currently available.'
GPT_INSTRUCTION = f"""
Answer the following questions as best you can. You have access to the following APIs:
{tools_instructions}
Use the following format:
```tool_json
{REUTRN_FORMAT}
```
Please choose the appropriate tool according to the user's question. If you don't need to call it, please reply directly to the user's question. When the user communicates with you in a language other than English, you need to communicate with the user in the same language.
When you have enough information from the tool results, respond directly to the user with a text message without having to call the tool again.
"""
for message in history:
if message["role"] == "system":
message["content"] = system_prompt
if tools_list != []:
message["content"] += "\n" + TOOL_EAXMPLE + "\n" + GPT_INSTRUCTION + "\n"
if tools is not None:
print(tools)
tools = json.loads(tools)
max_length = int(max_length)
if file_content is not None:
user_prompt = (
"文件中相关内容:"
+ file_content
+ "\n"
+ "用户提问:"
+ user_prompt
+ "\n"
+ "请根据文件内容回答用户问题。\n"
+ "如果无法从文件内容中找到答案,请回答“抱歉,我无法从文件内容中找到答案。”"
)
if images is not None:
if imgbb_api_key == "" or imgbb_api_key is None:
imgbb_api_key = api_keys.get("imgbb_api")
if imgbb_api_key == "" or imgbb_api_key is None:
i = 255.0 * images[0].cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
# 将图片保存到缓冲区
buffered = io.BytesIO()
img.save(buffered, format="PNG")
# 将图片编码为base64
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
img_json = [
{"type": "text", "text": user_prompt},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{img_str}"},
},
]
user_prompt = img_json
else:
i = 255.0 * images[0].cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
# 将图片保存到缓冲区
buffered = io.BytesIO()
img.save(buffered, format="PNG")
# 将图片编码为base64
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
url = "https://api.imgbb.com/1/upload"
payload = {"key": imgbb_api_key, "image": img_str}
# 向API发送POST请求
response = requests.post(url, data=payload)
# 检查请求是否成功
if response.status_code == 200:
# 解析响应以获取图片URL
result = response.json()
img_url = result["data"]["url"]
else:
return "Error: " + response.text
img_json = [
{"type": "text", "text": user_prompt},
{
"type": "image_url",
"image_url": {
"url": img_url,
},
},
]
user_prompt = img_json
response, history = model.send(user_prompt, temperature, max_length, history, tools)
print(response)
# 修改prompt.json文件
history_get = [history[0]]
history_get.extend(history_copy)
history_get.extend(history[1:])
history = history_get
with open(self.prompt_path, "w", encoding="utf-8") as f:
json.dump(history, f, indent=4, ensure_ascii=False)
for his in history:
if his["role"] == "user":
# 如果his["content"]是个列表,则只保留"type" : "text"时的"text"属性内容
if isinstance(his["content"], list):
for item in his["content"]:
if item.get("type") == "text" and item.get("text"):
his["content"] = item["text"]
break
historys = ""
# 将history中的消息转换成便于用户阅读的markdown格式
for his in history:
if his["role"] == "user":
historys += f"**User:** {his['content']}\n\n"
elif his["role"] == "assistant":
historys += f"**Assistant:** {his['content']}\n\n"
elif his["role"] == "system":
historys += f"**System:** {his['content']}\n\n"
elif his["role"] == "observation":
historys += f"**Observation:** {his['content']}\n\n"
elif his["role"] == "tool":
historys += f"**Tool:** {his['content']}\n\n"
elif his["role"] == "function":
historys += f"**Function:** {his['content']}\n\n"
history = str(historys)
global image_buffer
image_out = image_buffer.copy()
image_buffer = []
if image_out == []:
image_out = None
return (
response,
history,
llm_tools_json,
image_out,
)
except Exception as ex:
print(ex)
return (
str(ex),
str(ex),
llm_tools_json,
None,
)
@classmethod
def IS_CHANGED(s):
# 生成当前时间的哈希值
hash_value = hashlib.md5(str(datetime.datetime.now()).encode()).hexdigest()
return hash_value
def llm_chat(model, tokenizer, user_prompt, history, device, max_length, role="user", temperature=0.7):
history.append({"role": role, "content": user_prompt.strip()})
text = tokenizer.apply_chat_template(history, tokenize=False, add_generation_prompt=True)
model_inputs = tokenizer([text], return_tensors="pt").to(device)
generated_ids = model.generate(
model_inputs.input_ids, max_new_tokens=max_length, temperature=temperature # Add the eos_token_id parameter
)
generated_ids = [
output_ids[len(input_ids) :] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
history.append({"role": "assistant", "content": response})
return response, history
class LLM_local_loader:
original_IS_CHANGED = None
def __init__(self):
self.id = hash(str(self))
self.device = ""
self.dtype = ""
self.model_type = ""
self.model_path = ""
self.tokenizer_path = ""
self.model = ""
self.tokenizer = ""
self.is_locked = False
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"model_name": ("STRING", {"default": ""}),
"model_type": (
["GLM", "llama", "Qwen"],
{
"default": "GLM",
},
),
"model_path": (
"STRING",
{
"default": None,
},
),
"tokenizer_path": (
"STRING",
{
"default": None,
},
),
"device": (
["auto", "cuda", "cpu", "mps"],
{
"default": "auto",
},
),
"dtype": (
["float32", "float16", "int8", "int4"],
{
"default": "float32",
},
),
"is_locked": ("BOOLEAN", {"default":True}),
}
}
RETURN_TYPES = (
"CUSTOM",
"CUSTOM",
)
RETURN_NAMES = (
"model",
"tokenizer",
)
FUNCTION = "chatbot"
# OUTPUT_NODE = False
CATEGORY = "大模型派对(llm_party)/加载器(loader)"
def chatbot(self, model_name, model_type, model_path, tokenizer_path, device, dtype,is_locked=False):
self.is_locked = is_locked
if LLM_local_loader.original_IS_CHANGED is None:
# 保存原始的IS_CHANGED方法的引用
LLM_local_loader.original_IS_CHANGED = LLM_local_loader.IS_CHANGED
if self.is_locked == False:
setattr(LLM_local_loader, "IS_CHANGED", LLM_local_loader.original_IS_CHANGED)
else:
# 如果方法存在,则删除
if hasattr(LLM_local_loader, "IS_CHANGED"):
delattr(LLM_local_loader, "IS_CHANGED")
if model_path != "" and tokenizer_path != "":
model_name = ""
if model_name in config_key:
model_path = config_key[model_name].get("model_path")
tokenizer_path = config_key[model_name].get("tokenizer_path")
elif model_name != "":
model_path = model_name