intent_judge.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # 标准库导入
  2. import time
  3. from functools import lru_cache
  4. from typing import Dict, List, Any, Optional
  5. # 第三方库导入
  6. from langchain.chains.base import Chain
  7. from pydantic import Field
  8. # 本地导入
  9. from utils.logger_config import setup_logger
  10. from utils.prompt_config import prompt_router
  11. from utils.rag_config import BaseMethod, BotMethod, ConfigManager
  12. # 配置
  13. logger = setup_logger(__name__)
  14. class Judge(Chain):
  15. """
  16. 意图识别判官,用于意图识别模块的评估
  17. 继承自Chain,并组合BotMethod的功能
  18. """
  19. # 声明Pydantic字段
  20. config_manager: ConfigManager = Field(default_factory=ConfigManager)
  21. bot_method: BotMethod = Field(default_factory=BotMethod)
  22. prompt_template: Any = None
  23. def __init__(self, sys_prompt, config_path=None):
  24. """
  25. 初始化意图判官
  26. Args:
  27. config_path: 配置文件路径,如果为None则使用默认路径
  28. """
  29. super().__init__()
  30. # 使用指定的配置文件初始化
  31. if config_path:
  32. self.config_manager = ConfigManager(config_path)
  33. self.bot_method = BotMethod(config_path)
  34. self._init_prompt_template(sys_prompt)
  35. def _init_prompt_template(self, sys_prompt) -> None:
  36. """初始化提示词模板"""
  37. try:
  38. self.prompt_template = prompt_router(sys_prompt)
  39. except Exception as e:
  40. logger.error(f"初始化提示词模板失败: {e}")
  41. raise
  42. @property
  43. def input_keys(self) -> List[str]:
  44. """定义输入键"""
  45. return ["question"]
  46. @property
  47. def output_keys(self) -> List[str]:
  48. """定义输出键"""
  49. return ["answer"]
  50. def _generate_answer(self, content: str, question: str, llm_answer: str) -> str:
  51. """
  52. 生成答案
  53. Args:
  54. content: 上下文信息
  55. Returns:
  56. 生成的答案
  57. Raises:
  58. Exception: 生成答案失败时抛出异常
  59. """
  60. try:
  61. prompt = self.prompt_template.format(
  62. content=content,
  63. question=question,
  64. llm_answer=llm_answer
  65. )
  66. return self.bot_method.model_config.llm(prompt).content
  67. except Exception as e:
  68. logger.error(f"生成答案失败: {e}")
  69. raise
  70. def _call(self, inputs: Dict[str, Any]) -> Dict[str, str]:
  71. """
  72. 处理用户输入并返回答案
  73. Returns:
  74. 包含答案的字典
  75. Raises:
  76. KeyError: 输入缺少必要字段
  77. Exception: 处理过程中的其他异常
  78. """
  79. try:
  80. # 参数解析
  81. content = inputs["content"]
  82. question = inputs["question"]
  83. llm_answer = inputs["llm_answer"]
  84. # 生成答案
  85. answer = self._generate_answer(content=content, question=question, llm_answer=llm_answer)
  86. logger.info(f"评估结果: {answer}")
  87. # 返回结果
  88. return {"answer": answer}
  89. except Exception as e:
  90. logger.error(f"处理问题失败: {e}")
  91. raise
  92. if __name__ == "__main__":
  93. # 使用示例
  94. chain = Judge(sys_prompt="intent_judge")
  95. try:
  96. content = "本商店支持全国顺丰包邮,提供运费险"
  97. question = "请问有运费险吗?"
  98. llm_answer = "亲亲,咱们是不提供运费险的呢~"
  99. result = chain.invoke({"content": content, "question": question, "llm_answer": llm_answer})
  100. print(f"回答: {result['answer']}")
  101. except Exception as e:
  102. logger.error(f"处理失败: {e}")