创建消息

消息(Message)是AgentScope中的核心概念,用于支持多模态数据、工具API、信息存储/交换以及提示构建。

一条消息包含四个字段:

  • 名称,

  • role,

  • content,以及

  • 元数据

这些字段的类型和描述如下所示:

消息对象中的字段

字段

类型

描述

名称

字符串

消息发送者的名称/身份

角色

Literal[
"system",
"assistant",
"user"
]

消息发送者的角色,必须是“system”、“assistant”或“user”中的一个。

内容

str | list[ContentBlock]

消息的数据,可以是字符串或块列表。

metadata

dict[str, JSONSerializableObject] | None

一个包含消息额外元数据的字典,通常用于结构化输出。

提示

  • 在具有多重身份的应用中,name字段用于区分不同身份。

  • 推荐使用metadata字段进行结构化输出,该字段不会被包含在提示构建中。

接下来,我们按对应的场景介绍content字段中支持的块。

from agentscope.message import (
    Msg,
    Base64Source,
    TextBlock,
    ThinkingBlock,
    ImageBlock,
    AudioBlock,
    VideoBlock,
    ToolUseBlock,
    ToolResultBlock,
)
import json

创建文本消息

通过提供 namerolecontent 字段创建消息对象。

msg = Msg(
    name="Jarvis",
    role="assistant",
    content="Hi! How can I help you?",
)

print(f"The name of the sender: {msg.name}")
print(f"The role of the sender: {msg.role}")
print(f"The content of the message: {msg.content}")
The name of the sender: Jarvis
The role of the sender: assistant
The content of the message: Hi! How can I help you?

创建多模态消息

消息类通过提供不同的内容块来支持多模态内容:

AgentScope中的多模态内容块

描述

示例

文本块

纯文本数据

TextBlock(
   type="text",
   text="Hello, world!"
)

ImageBlock

图像数据

ImageBlock(
   type="image",
   source=URLSource(
       type="url",
       url="https://example.com/image.jpg"
   )
)

AudioBlock

音频数据

AudioBlock(
   type="audio",
   source=URLSource(
       type="url",
       url="https://example.com/audio.mp3"
   )
)

VideoBlock

视频数据

VideoBlock(
   type="video",
   source=URLSource(
       type="url",
       url="https://example.com/video.mp4"
   )
)

针对 ImageBlockAudioBlockVideoBlock,您可以使用 Base64 编码字符串作为来源:

msg = Msg(
    name="Jarvis",
    role="assistant",
    content=[
        TextBlock(
            type="text",
            text="This is a multimodal message with base64 encoded data.",
        ),
        ImageBlock(
            type="image",
            source=Base64Source(
                type="base64",
                media_type="image/jpeg",
                data="/9j/4AAQSkZ...",
            ),
        ),
        AudioBlock(
            type="audio",
            source=Base64Source(
                type="base64",
                media_type="audio/mpeg",
                data="SUQzBAAAAA...",
            ),
        ),
        VideoBlock(
            type="video",
            source=Base64Source(
                type="base64",
                media_type="video/mp4",
                data="AAAAIGZ0eX...",
            ),
        ),
    ],
)

创建思考消息

ThinkingBlock 用于支持推理模型,包含模型的思考过程。

msg_thinking = Msg(
    name="Jarvis",
    role="assistant",
    content=[
        ThinkingBlock(
            type="thinking",
            thinking="I'm building an example for thinking block in AgentScope.",
        ),
        TextBlock(
            type="text",
            text="This is an example for thinking block.",
        ),
    ],
)

创建工具使用/结果消息

ToolUseBlockToolResultBlock用于支持工具API:

msg_tool_call = Msg(
    name="Jarvis",
    role="assistant",
    content=[
        ToolUseBlock(
            type="tool_use",
            id="343",
            name="get_weather",
            input={
                "location": "Beijing",
            },
        ),
    ],
)

msg_tool_res = Msg(
    name="system",
    role="system",
    content=[
        ToolResultBlock(
            type="tool_result",
            id="343",
            name="get_weather",
            output="The weather in Beijing is sunny with a temperature of 25°C.",
        ),
    ],
)

提示

更多关于智能体中工具API的信息,请参考工具章节。

序列化与反序列化

Message对象可以用to_dictfrom_dict方法分别进行序列化和反序列化。

serialized_msg = msg.to_dict()

print(type(serialized_msg))
print(json.dumps(serialized_msg, indent=4))
<class 'dict'>
{
    "id": "Xskieekyy62FcdRi8JDUyN",
    "name": "Jarvis",
    "role": "assistant",
    "content": [
        {
            "type": "text",
            "text": "This is a multimodal message with base64 encoded data."
        },
        {
            "type": "image",
            "source": {
                "type": "base64",
                "media_type": "image/jpeg",
                "data": "/9j/4AAQSkZ..."
            }
        },
        {
            "type": "audio",
            "source": {
                "type": "base64",
                "media_type": "audio/mpeg",
                "data": "SUQzBAAAAA..."
            }
        },
        {
            "type": "video",
            "source": {
                "type": "base64",
                "media_type": "video/mp4",
                "data": "AAAAIGZ0eX..."
            }
        }
    ],
    "metadata": null,
    "timestamp": "2025-09-08 07:54:40.895"
}

通过JSON格式字符串反序列化消息。

new_msg = Msg.from_dict(serialized_msg)

print(type(new_msg))
print(f'The sender of the message: "{new_msg.name}"')
print(f'The role of the sender: "{new_msg.role}"')
print(f'The content of the message: "{json.dumps(new_msg.content, indent=4)}"')
<class 'agentscope.message._message_base.Msg'>
The sender of the message: "Jarvis"
The role of the sender: "assistant"
The content of the message: "[
    {
        "type": "text",
        "text": "This is a multimodal message with base64 encoded data."
    },
    {
        "type": "image",
        "source": {
            "type": "base64",
            "media_type": "image/jpeg",
            "data": "/9j/4AAQSkZ..."
        }
    },
    {
        "type": "audio",
        "source": {
            "type": "base64",
            "media_type": "audio/mpeg",
            "data": "SUQzBAAAAA..."
        }
    },
    {
        "type": "video",
        "source": {
            "type": "base64",
            "media_type": "video/mp4",
            "data": "AAAAIGZ0eX..."
        }
    }
]"

属性函数

为了简化消息对象的使用,AgentScope 提供以下函数:
消息对象的功能

功能

参数

描述

get_text_content

-

将所有TextBlock中的内容收集到一个字符串中(用“\n”分隔)。

get_content_blocks

block_type

返回指定类型的内容块列表。如果未提供block_type,则以块格式返回内容。

has_content_blocks

block_type

检查消息是否含有指定类型的内容块。str内容被视为TextBlock类型。

脚本总运行时间:(0分钟0.004秒)

Gallery generated by Sphinx-Gallery