使用Langchain生成多视角查询
-
导入所需库:
pythonfrom langchain.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough from config import llm
-
设置提示模板:
pythonprompt = ChatPromptTemplate.from_template( """ You are an intelligent assistant. Your task is to generate 5 questions based on the provided question in different wording and different perspectives to retrieve relevant documents from a vector database. By generating multiple perspectives on the user question, your goal is to help the user overcome some of the limitations of the distance-based similarity search. Provide these alternative questions separated by newlines. Original question: {question} """ )
-
定义查询生成过程:
pythongenerate_queries = ( {"question": RunnablePassthrough()} | prompt | llm | StrOutputParser() | (lambda x: x.split("\n")) )
-
调用生成多视角查询:
pythonresult = generate_queries.invoke("温格高是如何赢下2023年环法自行车赛的?") print(result)
-
示例输出:
python[ "温格高在2023年环法自行车赛中采用了哪些策略?", "2023年环法自行车赛温格高获胜的关键因素是什么?", "温格高在2023年环法自行车赛中面对哪些挑战?", "温格高是如何准备2023年环法自行车赛的?", "2023年环法自行车赛温格高的表现有哪些亮点?" ]