AS AgentScopeAPI 手册 / API Reference

Msg

@JsonIgnoreProperties(ignoreUnknown = true) @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "role", visible = true, defaultImpl = Msg.class) @JsonSubTypes({ @JsonSubTypes.Type(value = UserMessage.class, name = "USER"), @JsonSubTypes.Type(value = AssistantMessage.class, name = "ASSISTANT"), @JsonSubTypes.Type(value = SystemMessage.class, name = "SYSTEM"), @JsonSubTypes.Type(value = ToolResultMessage.class, name = "TOOL"), }) public class Msg implements State
源码Source io/agentscope/core/message/Msg.java:54–883

Msg 是 Java 版的统一消息对象,由 MsgRole 与 ContentBlock 列表组成。构建器负责构造,getTextContent 与 getStructuredData 提供常用读取方式。位于 io.agentscope.core.message 包,实现 State。核心成员包括 builder、builderForRole、generateId、currentTimestamp、getId、getName。

Represents a message in the AgentScope framework.

Messages are the primary communication unit between agents, users, and tools. Each message has a role (user, assistant, system, or tool), content blocks, and optional metadata.

Content blocks can include text, images, audio, video, thinking content, tool use blocks, and tool result blocks. The content is stored as an immutable list for thread safety.

Messages are serialized to JSON using Jackson and include a unique ID for tracking purposes.

核心精讲Deep dive

Msg:Java 消息模型Msg: the Java message model

Msg 是 Java 版的统一消息对象,由 MsgRole 与 ContentBlock 列表组成。Builder 负责构造,getTextContent 与 getStructuredData 提供常用读取方式。

Msg is the unified message object in Java, composed of a MsgRole and a list of ContentBlock. The builder constructs messages, while getTextContent and getStructuredData provide common accessors.

  • builderForRole 是构造用户、助手消息的快捷入口。builderForRole is the shortcut for user and assistant messages.
  • getContentBlocks 按类型过滤文本、工具调用或工具结果块。getContentBlocks filters text, tool-use or tool-result blocks by type.
  • getStructuredData 把结构化输出反序列化为 record 或 POJO。getStructuredData deserializes structured output into a record or POJO.

构造并读取消息Build and read a message

import io.agentscope.core.message.Msg;
import io.agentscope.core.message.MsgRole;

public class MsgDemo {
    public static void main(String[] args) {
        Msg msg = Msg.builder()
                .name("user")
                .role(MsgRole.USER)
                .textContent("Hello")
                .build();

        System.out.println(msg.getTextContent());
        System.out.println(msg.getRole());
    }
}

嵌套类摘要Nested Class Summary

类Class类型Kind说明Description
Builder类class
构建器,用于构建并配置目标实例。
A class in io.agentscope.core.message that carries structured messages and events between agents, models and UIs.

字段摘要Field Summary

字段Field类型Type说明Description
METADATA_GENERATE_REASON
staticfinal
String
元数据 GENERATE 推理字段。
Metadata key for storing the generate reason.
METADATA_CONFIRM_RESULTS
staticfinal
String
元数据确认结果字段。
Metadata key for carrying a `List<ConfirmResult>` when resuming a Permission HITL pause.
METADATA_CONFIRM_REQUEST_REPLY_ID
staticfinal
String
元数据确认请求回复标识字段。
Metadata key storing the `replyId` of the `RequireUserConfirmEvent` that paused this assistant turn.
METADATA_EXTERNAL_EXECUTION_REQUEST_REPLY_ID
staticfinal
String
元数据外部执行请求回复标识字段。
Metadata key storing the `replyId` of the `RequireExternalExecutionEvent` that paused this assistant turn.
METADATA_SYNTHETIC
staticfinal
String
元数据 SYNTHETIC字段。
Metadata key (boolean) marking a message as *synthetic*: framework-injected rather than authored by the user, the model, or a tool.
METADATA_REMINDER_KIND
staticfinal
String
元数据 REMINDER 种类字段。
Metadata key (string) describing the kind of synthetic reminder carried by a message, e.g.

构造器摘要Constructor Summary

构造器Constructor说明Description
protected Msg(String id, String name, MsgRole role, List<ContentBlock> content, Map<String, Object> metadata, String timestamp, ChatUsage usage)
初始化 `Msg` 实例。
Creates a new message with the specified fields.

方法摘要Method Summary

方法Method说明Description
public static Builder builder()
static
创建消息构建器。
Creates a new message builder with a randomly generated ID.
public static Builder builderForRole(MsgRole role)
static
按角色创建消息构建器。
Creates a builder for the concrete `Msg` subtype that matches the given role.
protected static String generateId()
static
返回 `generateId` 结果。
Generates a random UUID string for use as a message ID.
protected static String currentTimestamp()
static
返回当前时间戳。
Returns the current wall-clock timestamp in this class's canonical format.
public String getId()
获取标识。
Gets the unique identifier of this message.
public String getName()
获取可选名称的此消息。
Gets the optional name of this message.
public MsgRole getRole()
获取角色。
Gets the role of the message sender.
public List<ContentBlock> getContent()
获取内容。
Gets the immutable list of content blocks in this message.
public Map<String, Object> getMetadata()
获取元数据。
Gets the metadata associated with this message.
public String getTimestamp()
获取时间戳的此消息。
Gets the timestamp of this message.
public ChatUsage getUsage()
获取用量。
Gets the token usage information associated with this message.
public T extends ContentBlock boolean hasContentBlocks(Class<T> blockClass)
判断是否包含指定类型的内容块。
Check if this message has content blocks of the specified type (type-safe).
public T extends ContentBlock List<T> getContentBlocks(Class<T> blockClass)
按类型筛选内容块。
Get all content blocks of the specified type (type-safe).
public ContentBlock getFirstContentBlock()
获取第一个内容块。
Get the first content block, or null if empty.
public T extends ContentBlock T getFirstContentBlock(Class<T> blockClass)
获取第一个内容块。
Get the first content block of the specified type (type-safe).
public boolean hasStructuredData()
判断是否具有结构化数据。
Check if this message contains structured data in metadata.
public T T getStructuredData(Class<T> targetClass)
把结构化输出反序列化为目标类型。
Extract structured data from message metadata and convert it to the specified type.
public Map<String, Object> getStructuredData(boolean mutable)
把结构化输出反序列化为目标类型。
Extract structured data from message metadata and convert it to the java.util.Map.
public String getTextContent()
拼接并返回全部文本内容。
Extracts plain text content from this message.
public ChatUsage getChatUsage()
获取聊天用量。
Gets the chat usage statistics from this message's metadata.
public GenerateReason getGenerateReason()
获取 `getGenerateReason`。
Gets the reason why this message was generated.
public Msg withGenerateReason(GenerateReason reason)
执行 `withGenerateReason` 方法。
Creates a new message with the specified generate reason.
public Msg withContent(List<ContentBlock> newContent)
返回替换内容后的新消息。
Returns a copy of this message with the given content blocks.
public Msg withMetadata(Map<String, Object> newMetadata)
执行使用元数据相关操作。
Returns a copy of this message with the given metadata.

字段详情Field Detail

METADATA_GENERATE_REASON

public static final String METADATA_GENERATE_REASON
staticfinal

元数据 GENERATE 推理字段。声明为 public static final String METADATA_GENERATE_REASON。

Metadata key for storing the generate reason.

源码Source io/agentscope/core/message/Msg.java:70

METADATA_CONFIRM_RESULTS

public static final String METADATA_CONFIRM_RESULTS
staticfinal

元数据确认结果字段。声明为 public static final String METADATA_CONFIRM_RESULTS。

Metadata key for carrying a List when resuming a Permission HITL pause.

源码Source io/agentscope/core/message/Msg.java:77

METADATA_CONFIRM_REQUEST_REPLY_ID

public static final String METADATA_CONFIRM_REQUEST_REPLY_ID
staticfinal

元数据确认请求回复标识字段。声明为 public static final String METADATA_CONFIRM_REQUEST_REPLY_ID。

Metadata key storing the replyId of the RequireUserConfirmEvent that paused this assistant turn.

源码Source io/agentscope/core/message/Msg.java:83–84

METADATA_EXTERNAL_EXECUTION_REQUEST_REPLY_ID

public static final String METADATA_EXTERNAL_EXECUTION_REQUEST_REPLY_ID
staticfinal

元数据外部执行请求回复标识字段。声明为 public static final String METADATA_EXTERNAL_EXECUTION_REQUEST_REPLY_ID。

Metadata key storing the replyId of the RequireExternalExecutionEvent that paused this assistant turn.

源码Source io/agentscope/core/message/Msg.java:91–92

METADATA_SYNTHETIC

public static final String METADATA_SYNTHETIC
staticfinal

元数据 SYNTHETIC字段。声明为 public static final String METADATA_SYNTHETIC。

Metadata key (boolean) marking a message as synthetic: framework-injected rather than authored by the user, the model, or a tool.

源码Source io/agentscope/core/message/Msg.java:102

METADATA_REMINDER_KIND

public static final String METADATA_REMINDER_KIND
staticfinal

元数据 REMINDER 种类字段。声明为 public static final String METADATA_REMINDER_KIND。

Metadata key (string) describing the kind of synthetic reminder carried by a message, e.g.

源码Source io/agentscope/core/message/Msg.java:108

构造器详情Constructor Detail

Msg

protected Msg(String id, String name, MsgRole role, List<ContentBlock> content, Map<String, Object> metadata, String timestamp, ChatUsage usage)

初始化 Msg 实例。

Creates a new message with the specified fields.

参数Parameters
名称Name类型Type说明Description
idString标识(类型 `String`)。Unique identifier for the message
nameString名称(类型 `String`)。Optional name for the message (can be null)
roleMsgRole角色(类型 `MsgRole`)。The role of the message sender (user, assistant, system, or tool)
contentList<ContentBlock>内容(类型 `List`)。List of content blocks that make up the message content
metadataMap<String, Object>元数据(类型 `Map`)。Optional metadata map for additional information
timestampString时间戳(类型 `String`)。Optional timestamp string (if null, will be generated automatically)
usageChatUsage用量(类型 `ChatUsage`)。The usage.
源码Source io/agentscope/core/message/Msg.java:137–167

方法详情Method Detail

builder

public static Builder builder()
static

返回构建器实例。

Creates a new message builder with a randomly generated ID.

返回Returns Builder
一种新的构建器实例。A new builder instance
源码Source io/agentscope/core/message/Msg.java:220–222

builderForRole

public static Builder builderForRole(MsgRole role)
static

设置构建器用于角色。

Creates a builder for the concrete Msg subtype that matches the given role.

参数Parameters
名称Name类型Type说明Description
roleMsgRole角色(类型 `MsgRole`)。the role whose concrete message subtype should be built
返回Returns Builder
返回当前实例,以支持链式调用。a role-specific builder, or the base builder when `role` is `null`
源码Source io/agentscope/core/message/Msg.java:240–250

generateId

protected static String generateId()
static

返回 generateId 结果。

Generates a random UUID string for use as a message ID.

返回Returns String
返回字符串结果。Returns a string.
源码Source io/agentscope/core/message/Msg.java:257–259

currentTimestamp

protected static String currentTimestamp()
static

返回当前时间戳。

Returns the current wall-clock timestamp in this class's canonical format.

返回Returns String
返回字符串结果。Returns a string.
源码Source io/agentscope/core/message/Msg.java:266–268

getId

public String getId()

获取标识。

Gets the unique identifier of this message.

返回Returns String
消息标识。The message ID
源码Source io/agentscope/core/message/Msg.java:275–277

getName

public String getName()

获取可选名称的此消息。

Gets the optional name of this message.

返回Returns String
返回字符串结果。The message name, or null if not set
源码Source io/agentscope/core/message/Msg.java:284–286

getRole

public MsgRole getRole()

获取角色。

Gets the role of the message sender.

返回Returns MsgRole
返回MsgRole。The message role (user, assistant, system, or tool)
源码Source io/agentscope/core/message/Msg.java:293–295

getContent

public List<ContentBlock> getContent()

获取内容。

Gets the immutable list of content blocks in this message.

返回Returns List<ContentBlock>
返回列出。The content blocks list, may be empty but never null
源码Source io/agentscope/core/message/Msg.java:302–304

getMetadata

public Map<String, Object> getMetadata()

获取元数据。

Gets the metadata associated with this message.

返回Returns Map<String, Object>
返回映射。The metadata map, or null if not set
源码Source io/agentscope/core/message/Msg.java:311–313

getTimestamp

public String getTimestamp()

获取时间戳的此消息。

Gets the timestamp of this message.

返回Returns String
返回字符串结果。The timestamp string in format "yyyy-MM-dd HH:mm:ss.SSS"
源码Source io/agentscope/core/message/Msg.java:320–322

getUsage

public ChatUsage getUsage()

获取用量。

Gets the token usage information associated with this message.

返回Returns ChatUsage
返回ChatUsage。The usage object, or null if not available
源码Source io/agentscope/core/message/Msg.java:333–335

hasContentBlocks

public T extends ContentBlock boolean hasContentBlocks(Class<T> blockClass)

判断是否具有 hasContentBlocks。

Check if this message has content blocks of the specified type (type-safe).

参数Parameters
名称Name类型Type说明Description
blockClassClass<T>块类(类型 `Class`)。Block class to check for
返回Returns boolean
返回布尔值,表示判断结果。true if at least one block of the type exists
源码Source io/agentscope/core/message/Msg.java:344–348

getContentBlocks

public T extends ContentBlock List<T> getContentBlocks(Class<T> blockClass)

获取 getContentBlocks。

Get all content blocks of the specified type (type-safe).

参数Parameters
名称Name类型Type说明Description
blockClassClass<T>块类(类型 `Class`)。Block class to filter for
返回Returns List<T>
返回列出。List of matching blocks
源码Source io/agentscope/core/message/Msg.java:357–364

getFirstContentBlock

public ContentBlock getFirstContentBlock()

获取第一个内容块。

Get the first content block, or null if empty.

返回Returns ContentBlock
返回ContentBlock。First content block or null
源码Source io/agentscope/core/message/Msg.java:371–375

getFirstContentBlock

public T extends ContentBlock T getFirstContentBlock(Class<T> blockClass)

获取第一个内容块。

Get the first content block of the specified type (type-safe).

参数Parameters
名称Name类型Type说明Description
blockClassClass<T>块类(类型 `Class`)。Block class to search for
返回Returns T
返回T。First matching block or null
源码Source io/agentscope/core/message/Msg.java:384–392

hasStructuredData

public boolean hasStructuredData()

判断是否具有结构化数据。

Check if this message contains structured data in metadata.

返回Returns boolean
返回布尔值,表示判断结果。true if metadata is present and non-empty
源码Source io/agentscope/core/message/Msg.java:399–403

getStructuredData

public T T getStructuredData(Class<T> targetClass)

获取结构化数据。

Extract structured data from message metadata and convert it to the specified type.

参数Parameters
名称Name类型Type说明Description
targetClassClass<T>目标类(类型 `Class`)。The class to convert metadata into
返回Returns T
结构化数据对象。The structured data object
抛出Throws
  • IllegalStateException 可能抛出 `IllegalStateException`。if no metadata exists
  • IllegalArgumentException 可能抛出 `IllegalArgumentException`。if conversion fails
源码Source io/agentscope/core/message/Msg.java:429–453

getStructuredData

public Map<String, Object> getStructuredData(boolean mutable)

获取结构化数据。

Extract structured data from message metadata and convert it to the java.util.Map.

参数Parameters
名称Name类型Type说明Description
mutableboolean可变(类型 `boolean`)。The mutable.
返回Returns Map<String, Object>
返回映射。The copied metadata
抛出Throws
  • IllegalStateException 可能抛出 `IllegalStateException`。if no metadata exists
源码Source io/agentscope/core/message/Msg.java:503–532

getTextContent

public String getTextContent()

获取文本内容。

Extracts plain text content from this message.

返回Returns String
拼接后的文本内容。The concatenated text content from all text blocks, or empty string if none
源码Source io/agentscope/core/message/Msg.java:542–550

getChatUsage

public ChatUsage getChatUsage()

获取聊天用量。

Gets the chat usage statistics from this message's metadata.

返回Returns ChatUsage
返回ChatUsage。The ChatUsage object containing token counts and timing, or null if not available
源码Source io/agentscope/core/message/Msg.java:577–607

getGenerateReason

public GenerateReason getGenerateReason()

获取 getGenerateReason。

Gets the reason why this message was generated.

返回Returns GenerateReason
返回GenerateReason。The generate reason, defaults to `GenerateReason#MODEL_STOP` if not set
源码Source io/agentscope/core/message/Msg.java:639–657

withGenerateReason

public Msg withGenerateReason(GenerateReason reason)

执行 withGenerateReason 方法。

Creates a new message with the specified generate reason.

参数Parameters
名称Name类型Type说明Description
reasonGenerateReason原因(类型 `GenerateReason`)。The generate reason to set
返回Returns Msg
返回消息。A new Msg instance with the updated generate reason
源码Source io/agentscope/core/message/Msg.java:668–679

withContent

public Msg withContent(List<ContentBlock> newContent)

执行使用内容相关操作。

Returns a copy of this message with the given content blocks.

参数Parameters
名称Name类型Type说明Description
newContentList<ContentBlock>新建内容(类型 `List`)。the replacement content blocks
返回Returns Msg
返回消息。a new Msg with identical metadata but replaced content
源码Source io/agentscope/core/message/Msg.java:687–696

withMetadata

public Msg withMetadata(Map<String, Object> newMetadata)

执行使用元数据相关操作。

Returns a copy of this message with the given metadata.

参数Parameters
名称Name类型Type说明Description
newMetadataMap<String, Object>新建元数据(类型 `Map`)。the replacement metadata
返回Returns Msg
返回消息。a new Msg with identical content but replaced metadata
源码Source io/agentscope/core/message/Msg.java:704–713

嵌套类详情Nested Class Detail

Builder

public static class Builder

构建器,用于构建并配置目标实例。位于 io.agentscope.core.message 包。核心成员包括 id、name、role、content、textContent、metadata。

A class in io.agentscope.core.message that carries structured messages and events between agents, models and UIs. Declared in io.agentscope.core.message.

基于官方固定版本源码静态生成Generated from pinned official sources · Python 2.0.11 · Java 2.0.4
签名与文档为静态抽取;如有疑问请以源码为准。Signatures and docs are extracted statically; verify against the source when in doubt.