# 如何从ConversationChain迁移到LCEL实现,提升你的对话体验
## 引言
在使用Python进行对话智能应用开发时,掌握使用先进的对话链工具是必不可少的。Langchain提供的`ConversationChain`和`LCEL`(Langchain Conversational Execution Layer)都是流行的选择。本文将介绍从`ConversationChain`迁移到`LCEL`的过程,分析其优势,并提供实用的代码示例,帮助您提升对话体验。
## 主要内容
### 为什么选择LCEL?
LCEL相较于传统的`ConversationChain`具有以下几个显著优势:
1. **支持线程和独立会话**:LCEL支持多线程和独立会话,非常方便实现复杂的对话逻辑。
2. **显式参数设计**:相比之下,`ConversationChain`的隐藏默认提示容易造成混淆,LCEL提供了更明确的参数配置。
3. **支持流式输出**:LCEL原生支持流式输出,更适合实时应用。
### 代码实现对比
#### Legacy:使用ConversationChain
```python
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)
# 输出: "Arr matey, I be doin' well on the high seas, plunderin' and pillagin' as usual. How be ye?"
LCEL:使用RunnableWithMessageHistory
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)
# 输出: "Arr, me matey! I be doin' well, sailin' the high seas and searchin' for treasure. How be ye?"
常见问题和解决方案
-
如何处理不同会话的历史?
使用LCEL,您可以为不同的会话创建独立的历史记录。如下所示:
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", ) response = wrapped_chain.invoke( {"input": "Hello!"}, config={"configurable": {"session_id": "abc123"}}, ) print(response) # 输出: "Ahoy there, me hearty! What can this old pirate do for ye today?"
总结和进一步学习资源
在对话智能应用开发中,切换到LCEL实现可以为您提供更强大的功能和更高的灵活性。除了更好的会话管理,LCEL的显式参数和流式支持让开发更简单高效。对于进一步的学习,建议阅读Langchain的完整文档以及相关的教程。
参考资料
- Langchain Documentation: Langchain Official Docs
- Langchain API Reference: Langchain API
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---