类 Msg

java.lang.Object
io.agentscope.core.message.Msg
所有已实现的接口:
State

public class Msg extends Object implements State
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.

  • 字段详细资料

    • METADATA_GENERATE_REASON

      public static final String METADATA_GENERATE_REASON
      Metadata key for storing the generate reason.
      另请参阅:
  • 方法详细资料

    • builder

      public static Msg.Builder builder()
      Creates a new message builder with a randomly generated ID.
      返回:
      A new builder instance
    • getId

      public String getId()
      Gets the unique identifier of this message.
      返回:
      The message ID
    • getName

      public String getName()
      Gets the optional name of this message.
      返回:
      The message name, or null if not set
    • getRole

      public MsgRole getRole()
      Gets the role of the message sender.
      返回:
      The message role (user, assistant, system, or tool)
    • getContent

      public List<ContentBlock> getContent()
      Gets the immutable list of content blocks in this message.
      返回:
      The content blocks list, may be empty but never null
    • getMetadata

      public Map<String,Object> getMetadata()
      Gets the metadata associated with this message.
      返回:
      The metadata map, or null if not set
    • getTimestamp

      public String getTimestamp()
      Gets the timestamp of this message.
      返回:
      The timestamp string in format "yyyy-MM-dd HH:mm:ss.SSS"
    • hasContentBlocks

      public <T extends ContentBlock> boolean hasContentBlocks(Class<T> blockClass)
      Check if this message has content blocks of the specified type (type-safe).
      类型参数:
      T - Content block type
      参数:
      blockClass - Block class to check for
      返回:
      true if at least one block of the type exists
    • getContentBlocks

      public <T extends ContentBlock> List<T> getContentBlocks(Class<T> blockClass)
      Get all content blocks of the specified type (type-safe).
      类型参数:
      T - Content block type
      参数:
      blockClass - Block class to filter for
      返回:
      List of matching blocks
    • getFirstContentBlock

      public ContentBlock getFirstContentBlock()
      Get the first content block, or null if empty.
      返回:
      First content block or null
    • getFirstContentBlock

      public <T extends ContentBlock> T getFirstContentBlock(Class<T> blockClass)
      Get the first content block of the specified type (type-safe).
      类型参数:
      T - Content block type
      参数:
      blockClass - Block class to search for
      返回:
      First matching block or null
    • hasStructuredData

      public boolean hasStructuredData()
      Check if this message contains structured data in metadata.
      返回:
      true if metadata is present and non-empty
    • getStructuredData

      public <T> T getStructuredData(Class<T> targetClass)
      Extract structured data from message metadata and convert it to the specified type.

      This method is useful when the message contains structured input from a user agent or structured output from an LLM. The metadata map is converted to a Java object using Jackson's ObjectMapper.

      Example usage:

      
       public class TaskPlan {
           public String goal;
           public int priority;
       }
      
       Msg msg = userAgent.call(null, TaskPlan.class).block();
       TaskPlan plan = msg.getStructuredData(TaskPlan.class);
       
      类型参数:
      T - Type of the structured data
      参数:
      targetClass - The class to convert metadata into
      返回:
      The structured data object
      抛出:
      IllegalStateException - if no metadata exists
      IllegalArgumentException - if conversion fails
    • getStructuredData

      public Map<String,Object> getStructuredData(boolean mutable)
      Extract structured data from message metadata and convert it to the java.util.Map.

      This method is useful when the message contains structured input from a user agent or structured output from an LLM. support for using dynamic schema processing

      Example usage:

      
       String json = """
               {
                       						 "type": "object",
                       						 "properties": {
                       						   "productName": {
                       							 "type": "string"
                       						                                              },
                       						   "features": {
                       							 "type": "array",
                       							 "items": {
                       							   "type": "string"                                             *                                           }
                       						   },
                       						   "pricing": {
                       							 "type": "object",
                       							 "properties": {
                       							   "amount": {
                                                        e": "number"
                       							   },
                       							   "currency": {
                                                        e": "string"
                                                   }
                                                 }
                       						   },
                       						   "ratings": {
                       							 "type": "object",
                       							 "additionalProperties": {
                                                         e": "integer"
                                                 }
                                               }
                                             }
                       					   }
               """;
        JsonNode sampleJsonNode = new ObjectMapper().readTree(json);
         Msg msg = agent.call(input, sampleJsonNode).block(TEST_TIMEOUT);
         Map<String, Object> structuredData = msg.getStructuredData(false);
       
      返回:
      The copied metadata
      抛出:
      IllegalStateException - if no metadata exists
    • getTextContent

      public String getTextContent()
      Extracts plain text content from this message.

      This method concatenates all text blocks in the message, joined by newlines. If the message contains no text blocks, an empty string is returned.

      返回:
      The concatenated text content from all text blocks, or empty string if none
    • getChatUsage

      public ChatUsage getChatUsage()
      Gets the chat usage statistics from this message's metadata.

      This method retrieves the accumulated token usage information that was recorded during model generation. Returns null if no usage information is available.

      Example usage:

      
       Msg response = agent.call(userMsg).block();
       ChatUsage usage = response.getChatUsage();
       if (usage != null) {
           System.out.println("Input tokens: " + usage.getInputTokens());
           System.out.println("Output tokens: " + usage.getOutputTokens());
           System.out.println("Total tokens: " + usage.getTotalTokens());
           System.out.println("Time: " + usage.getTime() + "s");
       }
       
      返回:
      The ChatUsage object containing token counts and timing, or null if not available
    • getGenerateReason

      public GenerateReason getGenerateReason()
      Gets the reason why this message was generated.

      This method helps users understand the context of agent execution:

      返回:
      The generate reason, defaults to GenerateReason.MODEL_STOP if not set
    • withGenerateReason

      public Msg withGenerateReason(GenerateReason reason)
      Creates a new message with the specified generate reason.

      This method returns a new Msg instance with the updated generate reason stored in metadata. The original message is not modified (immutable).

      参数:
      reason - The generate reason to set
      返回:
      A new Msg instance with the updated generate reason