基于LangChain,如何让开源LLM自动选择直接回答或Retrieval QA
解决方案:基于LangChain+开源LLM实现自动回答/检索分支逻辑
核心是通过意图分类让开源LLM(如Llama)判断问题类型,再触发对应逻辑:无需检索的通用问题直接回答,业务相关问题调用Retrieval QA。以下是具体实现步骤:
1. 明确问题分类边界
先给LLM清晰的分类规则,避免歧义:
- 直接回答类:问候语(如“你好”“再见”)、闲聊(如“你叫什么”“今天心情怎么样”)、通用常识类(不涉及航空业务专属信息)
- 检索调用类:涉及PNR/邮箱的用户信息查询、航空条款(如退票/行李规则)、订单状态查询等需要从结构化SQL或非结构化PDF获取的信息
2. 用开源LLM构建意图分类链
借助LangChain的LLMChain结合Few-Shot Prompting提升分类准确率(开源模型对示例的依赖更强):
from langchain.llms import CTransformers from langchain.prompts import FewShotPromptTemplate, PromptTemplate from langchain.chains import LLMChain # 加载本地Llama模型(示例用CTransformers,也可用HuggingFacePipeline) llm = CTransformers(model="llama-2-7b-chat.ggmlv3.q4_0.bin", model_type="llama") # 定义分类示例 examples = [ {"question": "你好呀", "category": "direct_answer"}, {"question": "帮我查PNR为XYZ789的订单", "category": "retrieval_qa"}, {"question": "行李托运最多能带多少公斤", "category": "retrieval_qa"}, {"question": "再见", "category": "direct_answer"}, {"question": "你们能提供什么服务", "category": "direct_answer"} ] # 构建示例模板 example_template = """ Question: {question} Category: {category} """ example_prompt = PromptTemplate( input_variables=["question", "category"], template=example_template ) # 构建分类Prompt前缀 prefix = """你是一个航空机器人的意图分类器,需要将用户的问题分为两类: - direct_answer:无需检索,直接回答的通用问题(问候、闲聊、机器人功能介绍等) - retrieval_qa:需要调用检索工具获取信息的业务问题(PNR查询、航空条款、订单信息等) 请严格按照以下示例进行分类,只输出分类结果:""" suffix = """ Question: {user_question} Category:""" # 组装Few-Shot Prompt few_shot_prompt = FewShotPromptTemplate( examples=examples, example_prompt=example_prompt, prefix=prefix, suffix=suffix, input_variables=["user_question"], example_separator="\n\n" ) # 创建分类链 classification_chain = LLMChain(llm=llm, prompt=few_shot_prompt)
3. 实现分支逻辑
根据分类结果,触发不同的处理流程:
def handle_user_question(user_question): # 调用分类链获取结果 category = classification_chain.run(user_question).strip() if category == "direct_answer": # 直接用LLM生成回答 response = llm.invoke(user_question) return response elif category == "retrieval_qa": # 触发已有的Retrieval QA流程(SQL检索+PDF检索) # 这里替换成你已实现的Retrieval QA调用代码 retrieval_response = your_existing_retrieval_qa.run(user_question) return retrieval_response else: # 兜底处理,默认触发检索或直接回答 return llm.invoke("抱歉,我没理解你的问题,你可以再描述一下吗?")
4. 优化建议
- 扩充分类示例:覆盖更多场景(如模糊问题、边缘案例),提升开源LLM的分类准确率
- 本地模型调优:如果分类效果不佳,可以微调Llama模型,注入航空领域的意图分类数据
- 缓存分类结果:对重复问题的分类结果进行缓存,减少模型调用开销
内容的提问来源于stack exchange,提问作者prgarg007
相关产品推荐
相关产品推荐

