fixed_intent.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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.yaml_utils import fixed_question_intent_config
  20. class FixedIntentIdentifyClient:
  21. def __init__(self):
  22. """
  23. 创建意图识别类
  24. """
  25. # 获取部署的模型列表
  26. llm, chat, embed = get_models()
  27. self.llm_recognition = chat
  28. # 加载 意图识别系统配置信息
  29. self.intent_prompt = fixed_question_intent_config
  30. def recognize_intent(self, input):
  31. """
  32. 意图识别
  33. 输入:用户输入的问题
  34. 输出:识别出的意图,可选项:
  35. """
  36. # 准备few-shot样例
  37. examples = self.intent_prompt["fixed_problem_answer"]
  38. #server_logger.info(f"加载prompt配置.examples: {examples}")
  39. # 定义样本模板
  40. examples_prompt = ChatPromptTemplate.from_messages(
  41. [
  42. ("human", "{inn}"),
  43. ("ai", "{out}"),
  44. ]
  45. )
  46. few_shot_prompt = FewShotChatMessagePromptTemplate(example_prompt=examples_prompt,
  47. examples=examples)
  48. final_prompt = ChatPromptTemplate.from_messages(
  49. [
  50. ('system', self.intent_prompt["system_prompt"]),
  51. few_shot_prompt,
  52. ('human', '{input}'),
  53. ]
  54. )
  55. chain = final_prompt | self.llm_recognition
  56. result = chain.invoke(input=input)
  57. # 容错处理
  58. if hasattr(result, 'content'):
  59. # 如果 result 有 content 属性,使用它
  60. return result.content
  61. else:
  62. # 否则,直接返回 result
  63. return result
  64. fixed_intent_identify_client = FixedIntentIdentifyClient()
  65. if __name__ == '__main__':
  66. #input = "你好"
  67. #input = "我要查询信息" #result=cattle_farm_query
  68. input = "查询最近步数情况" #result=cattle_farm_query
  69. input = "这套系统给我带来了什么好处" #result=cattle_farm_warning_plan
  70. input = "建设数字化后给我带来了多少效益" #result=cattle_farm_warning_task_execute
  71. #input = "查询11基本信息"
  72. #input = "查询16号的信息,返回json"
  73. # input = "查询16号的信息,返回markdown"
  74. # input = "编号为0014的数据,返回JSON格式数据"
  75. # input = "查询0013的信息"
  76. # input = "查询0013的数据"
  77. # input = """
  78. result = fixed_intent_identify_client.recognize_intent(input)
  79. server_logger.info(f"input={input} ,result={result}")