| 6 | |
| 7 | |
| 8 | class ChatbotModel: |
| 9 | def __init__(self, scene_templates: dict): |
| 10 | self.scene_templates: dict = scene_templates |
| 11 | self.current_purpose: str = '' |
| 12 | self.processors = {} |
| 13 | |
| 14 | @staticmethod |
| 15 | def load_scene_processor(self, scene_config): |
| 16 | try: |
| 17 | processor_name = scene_config["processor"] |
| 18 | scene_parameters = scene_config["parameters"] |
| 19 | module = importlib.import_module(f"scene_processor.impl.{processor_name}") |
| 20 | class_name = filename_to_classname(processor_name) |
| 21 | print('module', module) |
| 22 | print('class_name', class_name) |
| 23 | class_ = getattr(module, class_name) |
| 24 | return class_(scene_parameters) |
| 25 | except (ImportError, AttributeError, KeyError): |
| 26 | raise ImportError(f"未找到场景处理器 scene_config: {scene_config}") |
| 27 | |
| 28 | def is_related_to_last_intent(self, user_input): |
| 29 | """ |
| 30 | 判断当前输入是否与上一次意图场景相关 |
| 31 | """ |
| 32 | if not self.current_purpose: |
| 33 | return False |
| 34 | prompt = f"判断当前用户输入内容与当前对话场景的关联性:\n\n当前对话场景: {self.scene_templates[self.current_purpose]['description']}\n当前用户输入: {user_input}\n\n这两次输入是否关联(仅回答是或否)?" |
| 35 | result = send_message(prompt, None) |
| 36 | return result == '是' |
| 37 | |
| 38 | def recognize_intent(self, user_input): |
| 39 | # 根据场景模板生成选项 |
| 40 | purpose_options = {} |
| 41 | purpose_description = {} |
| 42 | index = 1 |
| 43 | for template_key, template_info in self.scene_templates.items(): |
| 44 | purpose_options[str(index)] = template_key |
| 45 | purpose_description[str(index)] = template_info["description"] |
| 46 | index += 1 |
| 47 | options_prompt = "\n".join([f"{key}. {value} - 请回复{key}" for key, value in purpose_description.items()]) |
| 48 | options_prompt += "\n0. 其他场景 - 请回复0" |
| 49 | |
| 50 | # 发送选项给用户 |
| 51 | user_choice = send_message(f"有下面多种场景,需要你根据用户输入进行判断,只答选项\n{options_prompt}\n用户输入:{user_input}\n请回复序号:", user_input) |
| 52 | |
| 53 | print('purpose_options', purpose_options) |
| 54 | print('user_choice', user_choice) |
| 55 | # 根据用户选择获取对应场景 |
| 56 | if user_choice != '0': |
| 57 | self.current_purpose = purpose_options[user_choice] |
| 58 | |
| 59 | if self.current_purpose: |
| 60 | print(f"用户选择了场景:{self.scene_templates[self.current_purpose]['name']}") |
| 61 | # 这里可以继续处理其他逻辑 |
| 62 | else: |
| 63 | # 用户输入的选项无效的情况,可以进行相应的处理 |
| 64 | print("无效的选项,请重新选择") |
| 65 | |