构建插件函数
1 def get_response_from_plugins(name_space_p, post_type_p, user_state_p, data): 2 # 存储每个函数的结果 3 try: 4 message = str(data["message"]) 5 except: 6 message = "" 7 8 plugin_dir = 'plugins' 9 10 11 results = [] 12 # 遍历plugins目录下的所有文件 13 for filename in os.listdir(plugin_dir): 14 if filename.endswith('.py'): 15 plugin_path = os.path.join(plugin_dir, filename) 16 # 动态导入模块 17 spec = importlib.util.spec_from_file_location("plugin_module", plugin_path) 18 plugin_module = importlib.util.module_from_spec(spec) 19 spec.loader.exec_module(plugin_module) 20 21 # 获取模块中的所有函数及其优先级 22 functions_with_priority = [(getattr(plugin_module, func), getattr(plugin_module, func)._name_space, getattr(plugin_module, func)._priority, getattr(plugin_module, func)._function_type, getattr(plugin_module, func)._post_type, getattr(plugin_module, func)._user_state, getattr(plugin_module, func)._block) for func in dir(plugin_module) if callable(getattr(plugin_module, func)) and hasattr(getattr(plugin_module, func), '_priority')] 23 24 # 根据优先级对函数进行排序 25 functions_with_priority.sort(key=lambda x: x[1]) 26 27 result_serial = None # 初始值设为None 28 result_parallel = '' # 用于并行执行的结果串联 29 # 依次执行函数 30 for function, name_space, priority, function_type, post_type, user_state, block in functions_with_priority: 31 # 判断function_type、post_type和user_state是否满足特定条件 32 if function_type == "serial" and post_type == post_type_p and user_state == user_state_p and name_space == name_space_p: 33 if result_serial is None: 34 # 如果result为None,则根据函数参数类型设定初始值 35 if 'dict' in str(function.__annotations__.values()): 36 result_serial = {} 37 elif 'str' in str(function.__annotations__.values()): 38 result_serial = '' 39 # 可以根据其他可能的参数类型继续添加条件 40 result_serial = function(data=result_serial) # 将data作为参数传递给函数 41 # 如果block=True,则结束循环,不再执行后续函数 42 if getattr(function, '_block', True): 43 break 44 elif function_type == "parallel" and post_type == post_type_p and user_state == user_state_p and name_space == name_space_p: 45 result_parallel += f"{function(data)}" 46 result_parallel += "\n" 47 48 # 如果block=True,则结束循环,不再执行后续函数 49 if getattr(function, '_block', True): 50 break 51 52 # 将每个函数的结果存储起来 53 results.append(f"{result_parallel}" + "\n" + f"{result_serial}") 54 55 # 将所有结果组合起来 56 result = "\n".join(results) 57 58 # 输出结果 59 print(f"插件返回结果:{result}") 60 # 准备问题(将从插件获取的结果与当前问题拼接成上下文供LLM推理) 61 query = f"{result}" + f"{message}" 62 return query