[深入理解Conversational RAG:增强你的对话系统]

128 阅读3分钟

引言

在许多问答类应用中,我们希望允许用户进行连续对话,这意味着应用需要某种类型的“记忆”来保存过去的问题和答案,并将其融合到当前的思考中。这篇文章将介绍如何在LangChain中实现这种对话的记忆功能,并详细解释两种主要的方法:链(Chains)和代理(Agents)。

主要内容

链(Chains)

Chains总是会执行检索步骤,即使不需要也会如此。下面我们将通过构建一个基本的问答应用,展示如何使用LangChain中的链来实现这一功能。

依赖安装

首先,我们需要安装一些必要的Python包:

%%capture --no-stderr
%pip install --upgrade --quiet langchain langchain-community langchainhub langchain-chroma bs4

环境变量设置

在使用OpenAI API时,我们需要设置环境变量OPENAI_API_KEY

import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = getpass.getpass()

初始化LLM和其他工具

在本示例中,我们使用OpenAI的嵌入和Chroma向量存储:

from langchain_openai import ChatOpenAI
from langchain_chroma import Chroma
from langchain import hub
from langchain.chains import create_retrieval_chain
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain_community.document_loaders import WebBaseLoader
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
import bs4

# 初始化LLM
llm = ChatOpenAI(model="gpt-3.5-turbo")

构建问答应用

我们将构建一个简单的问答应用,通过加载博客内容、分块、索引来创建检索器:

# 加载、分块和索引博客内容
loader = WebBaseLoader(
    web_paths=("https://lilianweng.github.io/posts/2023-06-23-agent/",),
    bs_kwargs=dict(
        parse_only=bs4.SoupStrainer(
            class_=("post-content", "post-title", "post-header")
        )
    ),
)
docs = loader.load()
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
splits = text_splitter.split_documents(docs)
vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings())
retriever = vectorstore.as_retriever()

# 构建问答链
system_prompt = (
    "You are an assistant for question-answering tasks. "
    "Use the following pieces of retrieved context to answer "
    "the question. If you don't know the answer, say that you "
    "don't know. Use three sentences maximum and keep the "
    "answer concise."
    "\n\n"
    "{context}"
)
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", system_prompt),
        ("human", "{input}"),
    ]
)
question_answer_chain = create_stuff_documents_chain(llm, prompt)
rag_chain = create_retrieval_chain(retriever, question_answer_chain)

常见问题和解决方案

如何处理上下文不明确的问题?

当用户的问题涉及到历史对话内容时,我们需要将这些历史对话信息融入到当前问题中,以便更好地理解和回答。可以使用create_history_aware_retriever来实现上下文感知的检索。

from langchain.chains import create_history_aware_retriever
from langchain_core.prompts import MessagesPlaceholder

contextualize_q_system_prompt = (
    "Given a chat history and the latest user question "
    "which might reference context in the chat history, "
    "formulate a standalone question which can be understood "
    "without the chat history. Do NOT answer the question, "
    "just reformulate it if needed and otherwise return it as is."
)

contextualize_q_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", contextualize_q_system_prompt),
        MessagesPlaceholder("chat_history"),
        ("human", "{input}"),
    ]
)
history_aware_retriever = create_history_aware_retriever(
    llm, retriever, contextualize_q_prompt
)

代理(Agents)

与Chains不同,Agents可以在执行过程中做出决策,决定是否需要检索步骤。这使得Agents在处理复杂任务时更为灵活。

构建代理

首先,我们需要将检索器转换为LangChain工具:

from langchain.tools.retriever import create_retriever_tool

tool = create_retriever_tool(
    retriever,
    "blog_post_retriever",
    "Searches and returns excerpts from the Autonomous Agents blog post.",
)
tools = [tool]

接下来,我们使用LangGraph来创建代理:

from langgraph.prebuilt import create_react_agent

agent_executor = create_react_agent(llm, tools)

运行和验证

我们可以通过以下示例测试代理的行为:

query = "What is Task Decomposition?"

for s in agent_executor.stream(
    {"messages": [HumanMessage(content=query)]},
):
    print(s)
    print("----")

总结和进一步学习资源

这篇文章介绍了如何在LangChain中构建具有对话记忆的问答系统。通过使用Chains和Agents,可以实现更智能、更灵活的对话系统。此外,还可以通过深入学习LangChain的其他模块,如retrievers和Templates,进一步提升系统的能力。

参考资料

  1. LangChain 文档
  2. OpenAI API
  3. Chroma Documentation

结束语:'如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!' ---END---