【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年环法自行车赛温格高的表现有哪些亮点?"
    ]
相关推荐
Flynn Liang6 小时前
Agentic 工作流:子代理、Supervisor 与人工介入
java·langchain·多智能体·supervisor·agentic·langchain4j
GISer_Jing20 小时前
Agent核心内容
后端·ai·langchain
Flynn Liang1 天前
可观测性与成本治理:一次对话的 17 个观测点
java·langchain·可观测性·micrometer·langchain4j·token 成本·llm 监控
郝学胜-神的一滴1 天前
LangChain Skill 实现(渐进披露 On-Demand Skill,LangChain 官方 Deep Agent Skill 模式)
开发语言·python·langchain·numpy
Flynn Liang2 天前
Rerank 与上下文工程:重排、压缩与引用溯源的收益边界
langchain·rag·langchain4j·rerank·上下文工程·引用溯源
Flynn Liang2 天前
RAG 评估体系:黄金集、检索指标与 LLM-as-Judge 落地
java·langchain·rag·评估·langchain4j·检索指标
啊吧怪不啊吧3 天前
LangChain之绑定工具
langchain
努力的小郑4 天前
数据查到了,回答去哪儿了?一次百炼 + LangChain 排查实录
后端·langchain·agent
承渊政道5 天前
LangChainAI应用开发框架【LangChain与LangGraph介绍】
langchain·大模型·langgraph·ai应用开发
Flynn Liang5 天前
AiServices 源码级拆解:一个接口如何变成 RAG Agent
java·langchain·源码分析·rag·langchain4j·aiservices