类 Msg
- 所有已实现的接口:
State
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.
-
嵌套类概要
嵌套类 -
字段概要
字段修饰符和类型字段说明static final StringMetadata key for carrying aList<ConfirmResult>when resuming a Permission HITL pause.static final StringMetadata key for storing the generate reason.static final StringMetadata key (string) describing the kind of synthetic reminder carried by a message, e.g.static final StringMetadata key (boolean) marking a message as synthetic: framework-injected rather than authored by the user, the model, or a tool. -
构造器概要
构造器 -
方法概要
修饰符和类型方法说明static Msg.Builderbuilder()Creates a new message builder with a randomly generated ID.static Msg.BuilderbuilderForRole(MsgRole role) Creates a builder for the concreteMsgsubtype that matches the given role.protected static StringReturns the current wall-clock timestamp in this class's canonical format.protected static StringGenerates a random UUID string for use as a message ID.Gets the chat usage statistics from this message's metadata.Gets the immutable list of content blocks in this message.<T extends ContentBlock>
List<T> getContentBlocks(Class<T> blockClass) Get all content blocks of the specified type (type-safe).Get the first content block, or null if empty.<T extends ContentBlock>
TgetFirstContentBlock(Class<T> blockClass) Get the first content block of the specified type (type-safe).Gets the reason why this message was generated.getId()Gets the unique identifier of this message.Gets the metadata associated with this message.getName()Gets the optional name of this message.getRole()Gets the role of the message sender.getStructuredData(boolean mutable) Extract structured data from message metadata and convert it to the java.util.Map.<T> TgetStructuredData(Class<T> targetClass) Extract structured data from message metadata and convert it to the specified type.Extracts plain text content from this message.Gets the timestamp of this message.getUsage()Gets the token usage information associated with this message.<T extends ContentBlock>
booleanhasContentBlocks(Class<T> blockClass) Check if this message has content blocks of the specified type (type-safe).booleanCheck if this message contains structured data in metadata.withContent(List<ContentBlock> newContent) Returns a copy of this message with the given content blocks.withGenerateReason(GenerateReason reason) Creates a new message with the specified generate reason.
-
字段详细资料
-
METADATA_GENERATE_REASON
Metadata key for storing the generate reason.- 另请参阅:
-
METADATA_CONFIRM_RESULTS
Metadata key for carrying aList<ConfirmResult>when resuming a Permission HITL pause. The receivingReActAgent.call(msgs)extracts and applies these results to the ASKING tool calls in context.- 另请参阅:
-
METADATA_SYNTHETIC
Metadata key (boolean) marking a message as synthetic: framework-injected rather than authored by the user, the model, or a tool. Synthetic messages (e.g. the per-turn todo reminder produced byTaskReminderMiddleware) are appended transiently to the reasoning input and are not persisted intoAgentState.context; this flag lets any downstream consumer that does observe such a message recognise and skip it (memory extraction, compaction, RAG recall).- 另请参阅:
-
METADATA_REMINDER_KIND
Metadata key (string) describing the kind of synthetic reminder carried by a message, e.g."todo_state". Only meaningful whenMETADATA_SYNTHETICistrue.- 另请参阅:
-
-
构造器详细资料
-
Msg
protected Msg(String id, String name, MsgRole role, List<ContentBlock> content, Map<String, Object> metadata, String timestamp, ChatUsage usage) Creates a new message with the specified fields.- 参数:
id- Unique identifier for the messagename- Optional name for the message (can be null)role- The role of the message sender (user, assistant, system, or tool)content- List of content blocks that make up the message contentmetadata- Optional metadata map for additional informationtimestamp- Optional timestamp string (if null, will be generated automatically)
-
-
方法详细资料
-
builder
Creates a new message builder with a randomly generated ID.- 返回:
- A new builder instance
-
builderForRole
Creates a builder for the concreteMsgsubtype that matches the given role.Unlike
builder()(which produces a plainMsg), this factory returns the role-specific builder so the resulting instance is the appropriate subtype:UserMessageforMsgRole.USER,AssistantMessageforMsgRole.ASSISTANT,SystemMessageforMsgRole.SYSTEM, andToolResultMessageforMsgRole.TOOL. Anullrole falls back to the basebuilder().The returned builder's
build()is overridden covariantly, so the declaredMsg.Builderstatic type still yields the concrete subtype instance at runtime.- 参数:
role- the role whose concrete message subtype should be built- 返回:
- a role-specific builder, or the base builder when
roleisnull
-
generateId
Generates a random UUID string for use as a message ID. Exposed to subclasses so their convenience constructors can mirror the behaviour ofMsg.Builderwithout re-implementing UUID logic. -
currentTimestamp
Returns the current wall-clock timestamp in this class's canonical format. Exposed to subclasses so their convenience constructors can stamp messages identically toMsg.Builder. -
getId
Gets the unique identifier of this message.- 返回:
- The message ID
-
getName
Gets the optional name of this message.- 返回:
- The message name, or null if not set
-
getRole
Gets the role of the message sender.- 返回:
- The message role (user, assistant, system, or tool)
-
getContent
Gets the immutable list of content blocks in this message.- 返回:
- The content blocks list, may be empty but never null
-
getMetadata
Gets the metadata associated with this message.- 返回:
- The metadata map, or null if not set
-
getTimestamp
Gets the timestamp of this message.- 返回:
- The timestamp string in format "yyyy-MM-dd HH:mm:ss.SSS"
-
getUsage
Gets the token usage information associated with this message.Aligns with Python
Msg.usage(PR #1639). When populated, contains the input/output token counts from the model call that produced this message.- 返回:
- The usage object, or null if not available
-
hasContentBlocks
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
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
Get the first content block, or null if empty.- 返回:
- First content block or null
-
getFirstContentBlock
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
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 existsIllegalArgumentException- if conversion fails
-
getStructuredData
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
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
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
Gets the reason why this message was generated.This method helps users understand the context of agent execution:
GenerateReason.MODEL_STOP- Task completed normallyGenerateReason.TOOL_SUSPENDED- External tools need user executionGenerateReason.REASONING_STOP_REQUESTED- HITL stop in reasoning phaseGenerateReason.ACTING_STOP_REQUESTED- HITL stop in acting phaseGenerateReason.INTERRUPTED- Agent was interruptedGenerateReason.MAX_ITERATIONS- Maximum iterations reached
- 返回:
- The generate reason, defaults to
GenerateReason.MODEL_STOPif not set
-
withGenerateReason
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
-
withContent
Returns a copy of this message with the given content blocks.- 参数:
newContent- the replacement content blocks- 返回:
- a new Msg with identical metadata but replaced content
-