-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathllm.py
2997 lines (2856 loc) · 133 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 asyncio
import base64
import datetime
import gc
import glob
import hashlib
import importlib
import io
import json
import locale
import os
import random
import re
import sys
import time
import traceback
# import google.generativeai as genai
import numpy as np
import openai
import aisuite as ai
import requests
import torch
from PIL import Image
from transformers import (
AutoModel,
AutoModelForCausalLM,
AutoModelForSeq2SeqLM,
AutoModelForSequenceClassification,
AutoTokenizer,
GenerationConfig,
AutoConfig,
)
import PIL.Image
from openai import AzureOpenAI,OpenAI
if torch.cuda.is_available():
from transformers import BitsAndBytesConfig
from google.protobuf.struct_pb2 import Struct
from torchvision.transforms import ToPILImage
from .config_update import models_dict
from .config import config_key, config_path, current_dir_path, load_api_keys
from .tools.lorebook import Lorebook
from .tools.api_tool import (
api_function,
api_tool,
json2text,
list_append,
list_append_plus,
list_extend,
list_extend_plus,
parameter_combine,
parameter_combine_plus,
parameter_function,
use_api_tool,
)
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.clear_file import clear_file
from .tools.clear_model import clear_model
from .tools.custom_persona import custom_persona
from .tools.dialog import end_dialog, start_dialog,start_anything,end_anything
from .tools.dingding import Dingding, Dingding_tool, send_dingding
from .tools.end_work import end_workflow, img2path
from .tools.excel import image_iterator, load_excel,json_iterator,file_path_iterator
from .tools.feishu import feishu, feishu_tool, send_feishu
from .tools.file_combine import file_combine, file_combine_plus,string_combine, string_combine_plus
from .tools.get_time import get_time, time_tool
from .tools.get_weather import (
accuweather_tool,
get_accuweather,
)
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_function, 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, embeddings_function, save_ebd_database,load_ebd
from .tools.load_file import (
load_file,
load_file_folder,
load_img_path,
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.omost import omost_decode, omost_setting
from .tools.search_web import (
bing_loader,
bing_tool,
google_loader,
google_tool,
search_web,
search_web_bing,
duckduckgo_tool,
duckduckgo_loader,
search_duckduckgo,
)
from .tools.show_text import About_us, show_text_party
from .tools.smalltool import bool_logic, load_int, none2false,str2float,str2int,any2str,load_float,load_bool
from .tools.story import read_story_json, story_json_tool
from .tools.text_iterator import text_iterator,text_writing,json_writing
from .tools.tool_combine import tool_combine, tool_combine_plus
from .tools.translate_persona import translate_persona
from .tools.tts import openai_tts
from .tools.wechat import send_wechat, work_wechat, work_wechat_tool
from .tools.wikipedia import get_wikipedia, load_wikipedia, wikipedia_tool
from .tools.workflow import work_flow, workflow_tool, workflow_transfer
from .tools.flux_persona import flux_persona
from .tools.workflow_V2 import workflow_transfer_v2
_TOOL_HOOKS = [
"get_time",
"search_web",
"search_web_bing",
"check_web",
"interpreter",
"data_base",
"another_llm",
"use_api_tool",
"get_accuweather",
"get_wikipedia",
"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",
"search_duckduckgo",
]
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,
is_enable,
extra_parameters,
user_history,
img_URL,
) = 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,
is_enable,
extra_parameters,
user_history,
img_URL,
)
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,
is_enable,
extra_parameters,
user_history,
is_enable_system_role,
) = 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,
is_enable,
extra_parameters,
user_history,
is_enable_system_role,
)
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 '-' in tool_name and tool_name not in _TOOL_HOOKS:
from .custom_tool.mcp_cli import mcp_client as client
async def run_client():
try:
# Initialize the client (if necessary)
if client.is_initialized is False:
await client.initialize()
functions = await client.get_openai_functions()
# Call the tool and get the result
result = await client.call_tool(tool_name, tool_params)
return str(result)
except Exception as e:
return str(e)
# Run the async function using asyncio.run
return asyncio.run(run_client())
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 isinstance(ret_out, tuple):
ret = ret_out[0]
global image_buffer
image_buffer = ret_out[1]
if ret == "" or ret is None:
ret = "图片已生成。并以展示在本节点的image输出中。可以使用preview_image节点查看图片。"
else:
ret = ret_out
except:
ret = traceback.format_exc()
return str(ret)
"""
def convert_to_gemini(openai_history):
for entry in openai_history:
role = entry["role"]
if role == "system":
content = entry["content"]
return content
return ""
def convert_tool_to_gemini(openai_tools):
gemini_tools = []
for tool in openai_tools:
gemini_tool = {
"name": tool["function"]["name"],
"description": tool["function"]["description"],
"parameters": {
"type": "OBJECT",
"properties": {}
}
}
for prop_name, prop_details in tool["function"]["parameters"]["properties"].items():
gemini_tool["parameters"]["properties"][prop_name] = {
"type": prop_details["type"].upper(),
"description": prop_details["description"]
}
gemini_tool["parameters"]["required"] = tool["function"]["parameters"]["required"]
gemini_tools.append(gemini_tool)
return gemini_tools
class genChat:
def __init__(self, model_name, apikey) -> None:
self.model_name = model_name
self.apikey = apikey
def send(
self,
user_prompt,
temperature,
max_length,
history,
tools=None,
is_tools_in_sys_prompt="disable",
images=None,
imgbb_api_key="",
**extra_parameters,
):
try:
if tools is None:
tools = []
# Function to convert OpenAI history to Gemini history
System_prompt= convert_to_gemini(history)
if images is not None:
new_parts = [{"text": user_prompt}]
for image in images:
i = 255.0 * image.cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
new_parts.append({"inline_data": img})
new_message = {"role": "user", "parts": new_parts}
else:
new_message = {"role": "user", "parts": [{"text": user_prompt}]}
history.append(new_message)
tools = convert_tool_to_gemini(tools)
genai.configure(api_key=self.apikey)
tool_list={
'function_declarations': tools
}
if "n" in extra_parameters:
extra_parameters["candidate_count"]= extra_parameters["n"]
del extra_parameters["n"]
# 如果extra_parameters["response_format"]存在就删除它
if "response_format" in extra_parameters:
del extra_parameters["response_format"]
model = genai.GenerativeModel(self.model_name,tools=tool_list,system_instruction=System_prompt,generation_config={"response_mime_type": "application/json"})
else:
model = genai.GenerativeModel(self.model_name,tools=tool_list,system_instruction=System_prompt)
response = model.generate_content(
contents= history[1:],
generation_config={
"temperature": temperature,
"max_output_tokens": max_length,
**extra_parameters
}
)
if images is not None:
# 移除包含 "inline_data" 的部分
for message in history:
if "parts" in message:
message["parts"] = [part for part in message["parts"] if "inline_data" not in part]
while response.candidates[0].content.parts[0].function_call:
function_call =response.candidates[0].content.parts[0].function_call
name = function_call.name
args = {key:value for key, value in function_call.args.items()}
res={"role": "model", "parts": response.candidates[0].content.parts}
history.append(res)
print("正在调用" + name + "工具")
results = dispatch_tool(name, args)
s = Struct()
s.update({"result": results})
function_response = genai.protos.Part(
function_response=genai.protos.FunctionResponse(name=name, response=s)
)
res={
"role": "user",
"parts": [function_response]
}
print("调用结果:" + str(results))
history.append(res)
response = model.generate_content(
contents= history[1:],
generation_config={
"temperature": temperature,
"max_output_tokens": max_length,
**extra_parameters
}
)
# 移除history最后两个元素
history.pop()
history.pop()
text = response.candidates[0].content.parts[0].text
res={"role": "model", "parts": [{"text": text}]}
history.append(res)
except Exception as e:
return str(e), history
return text, history
"""
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,
is_tools_in_sys_prompt="disable",
images=None,
imgbb_api_key="",
img_URL=None,
**extra_parameters,
):
try:
if images is not None and (img_URL is None or img_URL == ""):
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:
img_json = [{"type": "text", "text": user_prompt}]
for image in images:
i = 255.0 * image.cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
img_json.append({
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{img_str}"}
})
user_prompt = img_json
else:
img_json = [{"type": "text", "text": user_prompt}]
for image in images:
i = 255.0 * image.cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
url = "https://api.imgbb.com/1/upload"
payload = {"key": imgbb_api_key, "image": img_str}
response = requests.post(url, data=payload)
if response.status_code == 200:
result = response.json()
img_url = result["data"]["url"]
img_json.append({
"type": "image_url",
"image_url": {"url": img_url}
})
else:
return "Error: " + response.text
user_prompt = img_json
elif img_URL is not None and img_URL != "":
user_prompt = [{"type": "text", "text": user_prompt}, {"type": "image_url", "image_url": {"url": img_URL}}]
# 将history中的系统提示词部分如果为空,就剔除
for i in range(len(history)):
if history[i]["role"] == "system" and history[i]["content"] == "":
history.pop(i)
break
if re.search(r'o[1-3]', self.model_name):
# 将history中的系统提示词部分的角色换成user
for i in range(len(history)):
if history[i]["role"] == "system":
history[i]["role"] = "user"
history.append({"role": "assistant", "content": "好的,我会按照你的指示来操作"})
break
openai_client = OpenAI(
api_key= self.apikey,
base_url=self.baseurl,
)
if "openai.azure.com" in self.baseurl:
# 获取API版本
api_version = self.baseurl.split("=")[-1].split("/")[0]
# 获取azure_endpoint
azure_endpoint = "https://"+self.baseurl.split("//")[1].split("/")[0]
azure = AzureOpenAI(
api_key= self.apikey,
api_version=api_version,
azure_endpoint=azure_endpoint,
)
openai_client = azure
new_message = {"role": "user", "content": user_prompt}
history.append(new_message)
print(history)
if "o1" in self.model_name:
if tools is not None:
response = openai_client.chat.completions.create(
model=self.model_name,
messages=history,
tools=tools,
**extra_parameters,
)
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,
}
)
response = openai_client.chat.completions.create(
model=self.model_name,
messages=history,
tools=tools,
**extra_parameters,
)
print(response)
elif is_tools_in_sys_prompt == "enable":
response = openai_client.chat.completions.create(
model=self.model_name,
messages=history,
**extra_parameters,
)
response_content = response.choices[0].message.content
# 正则表达式匹配
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_client.chat.completions.create(
model=self.model_name,
messages=history,
**extra_parameters,
)
response_content = response.choices[0].message.content
else:
response = openai_client.chat.completions.create(
model=self.model_name,
messages=history,
**extra_parameters,
)
print(response)
elif tools is not None:
response = openai_client.chat.completions.create(
model=self.model_name,
messages=history,
temperature=temperature,
tools=tools,
max_tokens=max_length,
**extra_parameters,
)
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_client.chat.completions.create(
model=self.model_name,
messages=history,
tools=tools,
temperature=temperature,
max_tokens=max_length,
**extra_parameters,
)
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_client.chat.completions.create(
model=self.model_name,
messages=history,
tools=tools,
temperature=temperature,
max_tokens=max_length,
**extra_parameters,
)
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_client.chat.completions.create(
model=self.model_name,
messages=history,
tools=tools,
temperature=temperature,
max_tokens=max_length,
**extra_parameters,
)
response_content = response.choices[0].message.content
print(response)
elif is_tools_in_sys_prompt == "enable":
response = openai_client.chat.completions.create(
model=self.model_name,
messages=history,
temperature=temperature,
max_tokens=max_length,
**extra_parameters,
)
response_content = response.choices[0].message.content
# 正则表达式匹配
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_client.chat.completions.create(
model=self.model_name,
messages=history,
temperature=temperature,
max_tokens=max_length,
**extra_parameters,
)
response_content = response.choices[0].message.content
else:
response = openai_client.chat.completions.create(
model=self.model_name,
messages=history,
temperature=temperature,
max_tokens=max_length,
**extra_parameters,
)
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 aisuite_Chat:
def __init__(self, provider,model_name, apikey, baseurl,aws_access_key_id,aws_secret_access_key, aws_region_name,google_project_id,google_region,google_application_credentials,hf_api_token) -> None:
self.model_name = f"{provider}:{model_name}"
self.apikey = apikey
self.baseurl = baseurl
self.provider_configs = {}
if provider == "openai":
self.provider_configs["openai"] ={
"api_key": apikey,
"base_url": baseurl if baseurl != "" else "https://api.openai.com/v1"
}
elif provider == "anthropic":
self.provider_configs["anthropic"] ={
"api_key": apikey,
"base_url": baseurl if baseurl != "" else "https://api.anthropic.com/v1"
}
elif provider == "azure":
self.provider_configs["azure"] ={
"api_key": apikey,
"base_url": baseurl if baseurl != "" else "https://openai.azure.com/"
}
elif provider == "aws":
os.environ['AWS_ACCESS_KEY'] = aws_access_key_id
os.environ['AWS_SECRET_KEY'] = aws_secret_access_key
os.environ['AWS_REGION_NAME'] = aws_region_name
elif provider == "google":
os.environ['GOOGLE_PROJECT_ID'] = google_project_id
os.environ['GOOGLE_REGION'] = google_region
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = google_application_credentials
elif provider == "huggingface":
os.environ['HUGGINGFACE_API_TOKEN'] = hf_api_token
def send(
self,
user_prompt,
temperature,
max_length,
history,
tools=None,
is_tools_in_sys_prompt="disable",
images=None,
imgbb_api_key="",
**extra_parameters,
):
try:
openai_client = ai.Client(self.provider_configs)
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:
img_json = [{"type": "text", "text": user_prompt}]
for image in images:
i = 255.0 * image.cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
img_json.append({
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{img_str}"}
})
user_prompt = img_json
else:
img_json = [{"type": "text", "text": user_prompt}]
for image in images:
i = 255.0 * image.cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
url = "https://api.imgbb.com/1/upload"
payload = {"key": imgbb_api_key, "image": img_str}
response = requests.post(url, data=payload)
if response.status_code == 200:
result = response.json()
img_url = result["data"]["url"]
img_json.append({
"type": "image_url",
"image_url": {"url": img_url}
})
else:
return "Error: " + response.text
user_prompt = img_json
# 将history中的系统提示词部分如果为空,就剔除
for i in range(len(history)):
if history[i]["role"] == "system" and history[i]["content"] == "":
history.pop(i)
break
new_message = {"role": "user", "content": user_prompt}
history.append(new_message)
print(history)
if tools is not None:
response = openai_client.chat.completions.create(
model=self.model_name,
messages=history,
temperature=temperature,
tools=tools,
max_tokens=max_length,
**extra_parameters,
)
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_client.chat.completions.create(
model=self.model_name,
messages=history,
tools=tools,
temperature=temperature,
max_tokens=max_length,
**extra_parameters,
)
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_client.chat.completions.create(
model=self.model_name,
messages=history,
tools=tools,
temperature=temperature,
max_tokens=max_length,
**extra_parameters,
)
print(response)