intent.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # !/usr/bin/ python
  2. # -*- coding: utf-8 -*-
  3. '''
  4. @Project : lq-agent-api
  5. @File :intent.py
  6. @IDE :PyCharm
  7. @Author :
  8. @Date :2025/7/14 12:04
  9. '''
  10. import os
  11. import sys
  12. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  13. from logger.loggering import server_logger
  14. from utils.utils import get_models
  15. from langchain_core.prompts import SystemMessagePromptTemplate
  16. from langchain_core.prompts import HumanMessagePromptTemplate
  17. from langchain_core.prompts import ChatPromptTemplate
  18. from langchain_core.prompts import FewShotChatMessagePromptTemplate
  19. from utils import yaml_utils
  20. from agent.session.session_manager import SessionContextMemoryManager
  21. from base.config import config_handler
  22. class IntentIdentifyClient:
  23. def __init__(self):
  24. """
  25. 创建意图识别类
  26. """
  27. # 获取部署的模型列表
  28. llm, chat, embed = get_models()
  29. self.llm_recognition = chat
  30. # 加载 意图识别系统配置信息
  31. self.intent_prompt = yaml_utils.get_intent_prompt()
  32. async def recognize_intent(self , trace_id: str , config: dict , input: str):
  33. """
  34. 意图识别
  35. 输入:用户输入的问题
  36. 输出:识别出的意图,可选项:
  37. - cattle_farm_common
  38. - cattle_farm_query
  39. - cattle_farm_warning_plan
  40. """
  41. session_id = config.sessionId
  42. use_history_recognize_intent = config_handler.get("lru", "USE_RECOGNIZE_INTENT_HISTORY_MESSAGES" , "False")
  43. server_logger.info(f"[使用用户最新历史记录作为意图识别]use_history_recognize_intent: {use_history_recognize_intent}")
  44. history = "无"
  45. if use_history_recognize_intent == "True":
  46. # 上下文管理器
  47. session_context_memory_manager = SessionContextMemoryManager(trace_id , session_id)
  48. # 获取内存最新的多少条历史记录(将消息列表序列化为字符串)
  49. history = await session_context_memory_manager.get_memory_last_history_str()
  50. # 根据历史记录和用户问题进行识别意图
  51. return self.recognize_intent_history(input=input , history=history)
  52. def recognize_intent_history(self , input: str , history="无"):
  53. """
  54. 意图识别
  55. 输入:用户输入的问题
  56. 输出:识别出的意图,可选项:
  57. - cattle_farm_common
  58. - cattle_farm_query
  59. - cattle_farm_warning_plan
  60. """
  61. # 准备few-shot样例
  62. examples = self.intent_prompt["intent_examples"]
  63. #server_logger.info(f"加载prompt配置.examples: {examples}")
  64. system_prompt = self.intent_prompt["system_prompt"]
  65. system_prompt = system_prompt.format(history=history)
  66. server_logger.info(f"增加用户历史记录,用于意图识别,prompt配置.system_prompt: {system_prompt}")
  67. # 定义样本模板
  68. examples_prompt = ChatPromptTemplate.from_messages(
  69. [
  70. ("human", "{inn}"),
  71. ("ai", "{out}"),
  72. ]
  73. )
  74. few_shot_prompt = FewShotChatMessagePromptTemplate(example_prompt=examples_prompt,
  75. examples=examples)
  76. final_prompt = ChatPromptTemplate.from_messages(
  77. [
  78. ('system', system_prompt),
  79. few_shot_prompt,
  80. ('human', '{input}'),
  81. ]
  82. )
  83. chain = final_prompt | self.llm_recognition
  84. server_logger.info(f"意图识别输入input: {input}")
  85. result = chain.invoke(input={"input": input})
  86. # 容错处理
  87. if hasattr(result, 'content'):
  88. # 如果 result 有 content 属性,使用它
  89. return result.content
  90. else:
  91. # 否则,直接返回 result
  92. return result
  93. intent_identify_client = IntentIdentifyClient()
  94. if __name__ == '__main__':
  95. #input = "你好"
  96. #input = "我要查询信息" #result=cattle_farm_query
  97. input = "查询最近步数情况" #result=cattle_farm_query
  98. input = "01、10"
  99. input = "继续"
  100. input = "当前没有"
  101. #input = "查询12步数"
  102. #input = "分析当前环境数据"
  103. result = intent_identify_client.recognize_intent_history(history=history , input=input)
  104. server_logger.info(f"result={result}")