# !/usr/bin/ python # -*- coding: utf-8 -*- ''' @Project : xiwu-agent-api @File :intent.py @IDE :PyCharm @Author :LINGMIN @Date :2025/7/14 12:04 ''' import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from foundation.observability.logger.loggering import server_logger from foundation.ai.models import get_models from langchain_core.prompts import SystemMessagePromptTemplate from langchain_core.prompts import HumanMessagePromptTemplate from langchain_core.prompts import ChatPromptTemplate from langchain_core.prompts import FewShotChatMessagePromptTemplate from foundation.utils import yaml_utils from foundation.infrastructure.config import config_handler class TestIntentIdentifyClient: def __init__(self): """ 创建意图识别类 """ # 获取部署的模型列表 llm, chat, embed = get_models() self.llm_recognition = chat # 加载 意图识别系统配置信息 self.intent_prompt = yaml_utils.get_intent_prompt() def recognize_intent(self , trace_id: str , config: dict , input: str): """ 意图识别 输入:用户输入的问题 输出:识别出的意图,可选项: """ session_id = config["session_id"] history = "无" # 根据历史记录和用户问题进行识别意图 return self.recognize_intent_history(input=input , history=history) def recognize_intent_history(self , input: str , history="无"): """ 意图识别 输入:用户输入的问题 输出:识别出的意图,可选项: """ # 准备few-shot样例 examples = self.intent_prompt["intent_examples"] #server_logger.info(f"加载prompt配置.examples: {examples}") system_prompt = self.intent_prompt["system_prompt"] system_prompt = system_prompt.format(history=history) server_logger.info(f"增加用户历史记录,用于意图识别,prompt配置.system_prompt: {system_prompt}") # 定义样本模板 examples_prompt = ChatPromptTemplate.from_messages( [ ("human", "{inn}"), ("ai", "{out}"), ] ) few_shot_prompt = FewShotChatMessagePromptTemplate(example_prompt=examples_prompt, examples=examples) final_prompt = ChatPromptTemplate.from_messages( [ ('system', system_prompt), few_shot_prompt, ('human', '{input}'), ] ) chain = final_prompt | self.llm_recognition server_logger.info(f"意图识别输入input: {input}") result = chain.invoke(input={"input": input}) # 容错处理 if hasattr(result, 'content'): # 如果 result 有 content 属性,使用它 return result.content else: # 否则,直接返回 result return result intent_identify_client = TestIntentIdentifyClient() if __name__ == '__main__': input = "你好" input = "查询课程" input = "操作" result = intent_identify_client.recognize_intent_history(history="" , input=input) server_logger.info(f"result={result}")