【langchain学习】使用Langchain生成多视角查询

使用Langchain生成多视角查询

  1. 导入所需库:

    python 复制代码
    from langchain.prompts import ChatPromptTemplate
    from langchain_core.output_parsers import StrOutputParser
    from langchain_core.runnables import RunnablePassthrough
    from config import llm
  2. 设置提示模板:

    python 复制代码
    prompt = 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}
        """
    )
  3. 定义查询生成过程:

    python 复制代码
    generate_queries = (
        {"question": RunnablePassthrough()}
        | prompt
        | llm
        | StrOutputParser()
        | (lambda x: x.split("\n"))
    )
  4. 调用生成多视角查询:

    python 复制代码
    result = generate_queries.invoke("温格高是如何赢下2023年环法自行车赛的?")
    print(result)
  5. 示例输出:

    python 复制代码
    [
        "温格高在2023年环法自行车赛中采用了哪些策略?",
        "2023年环法自行车赛温格高获胜的关键因素是什么?",
        "温格高在2023年环法自行车赛中面对哪些挑战?",
        "温格高是如何准备2023年环法自行车赛的?",
        "2023年环法自行车赛温格高的表现有哪些亮点?"
    ]
相关推荐
富贵儿9981 天前
NL2SQL 实践手记 04:多表查询为什么更难——让模型找对表、连对关系
数据库·sql·ai·自然语言处理·langchain
budingxiaomoli1 天前
LangChain与LangGraph介绍
人工智能·langchain
tong_li2 天前
给娃做个 AI 陪写作业助手:LangChain4j 入门(九):AI 分得清老大和老二(多用户隔离与 token 认证)
后端·langchain
东东吖3 天前
07-LangChain Agent智能助手构建笔记
langchain·llm·agent
deep_long3 天前
03|MCP 接入 LangChain Agent:stdio 与 Streamable HTTP 实战
langchain·mcp·mcp生产实践
东东吖3 天前
06-LangChain 结构化输出学习笔记
langchain·llm·agent
东东吖3 天前
04-LangChain Message 与提示词模板学习笔记
langchain·llm·agent
东东吖3 天前
03-LangSmith 使用学习笔记
langchain·llm·agent
东东吖3 天前
05-LangChain Tool 学习笔记
langchain·llm·agent
东东吖3 天前
02-LangChain 模型的创建与调用学习笔记
langchain·llm·agent