Class AbstractModelMessage<R extends Response>
java.lang.Object
uno.anahata.asi.agi.event.BasicPropertyChangeSource
uno.anahata.asi.agi.message.AbstractMessage
uno.anahata.asi.agi.message.AbstractModelMessage<R>
- Type Parameters:
R- The type of the model response.
- All Implemented Interfaces:
PropertyChangeSource, Rebindable
- Direct Known Subclasses:
AnthropicMessage, GeminiModelMessage, OpenAiCompatibleModelMessage, OpenAiModelMessage
Represents a message originating from the AI model. It extends
AbstractMessage, sets its role to MODEL, and provides
convenience methods for accessing tool calls. In the V2 simplified
architecture, this class acts as the atomic unit of a "turn", containing both
model content and any resulting tool calls/responses.- Author:
- anahata-gemini-pro-2.5
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate intThe number of billed completion (output) tokens for this candidate, as reported by the API.private intThe number of billed prompt (input) tokens for this candidate, as reported by the API.private StringThe citation metadata for the response, summarized as a string.private StringThe message explaining why the model stopped generating content for this candidate.private FinishReasonThe reason why the model stopped generating content for this candidate.private GroundingMetadataThe grounding metadata for the response.private StringThe ID of the AbstractModel that generated this message.private StringIf an AI provider produced this part and assigned an Id to it (e.g. an openai message id).private StringThe UUID of the AbstractAiProvider that generated this message.private StringThe raw JSON response from the model.private RThe response that returned this message.private booleanWhether a batch execution of all pending tools is actively underway on this message.private StringThe safety ratings for the response, summarized as a string.private booleanWhether the model is currently streaming content for this message.private final MapA turn scoped map for tools to store turn-scoped attributes.Fields inherited from class BasicPropertyChangeSource
propertyChangeSupportModifier and TypeFieldDescriptionprotected PropertyChangeSupportSupport for firing property change events. -
Constructor Summary
ConstructorsConstructorDescriptionAbstractModelMessage(@NonNull Agi agi, @NonNull String modelId) Constructs a new AbstractModelMessage. -
Method Summary
Modifier and TypeMethodDescriptionfinal BlobPartaddBlobPart(String mimeType, byte[] data) Creates and adds a new binary data part to this message.final ModelBlobPartaddBlobPart(String mimeType, byte[] data, byte[] thoughtSignature) Creates and adds a new model blob part with thought process metadata.final ModelBlobPartaddBlobPart(Path path) Creates and adds a new binary data part from a local file path.final TextPartaddTextPart(String text) Creates and adds a new text part to this message.final ModelTextPartaddTextPart(String text, byte[] thoughtSignature, boolean thought) Creates and adds a new model text part with thought process metadata.protected voidHook for subclasses to inject specialized metadata into the message header.voidappendRawJson(String chunk) Appends a raw JSON chunk to the existing content.voidSets all tool calls in this message that are currently in a PENDING state to DECLINED and collapses them.booleanExecutes all tool calls in this message that are currently in a PENDING state, sequentially checking runningAllPending before starting each tool call.Gets the ID of the device where this message was created or processed.getFrom()Gets the identity of the sender of this message.List<AbstractToolCall<?, ?>> Filters and returns all tool calls belonging to this model message that are currently awaiting execution inToolExecutionStatus.PENDINGstate.intCalculates the number of tool calls in this message that are currently active in the execution queue (either actively EXECUTING or still PENDING).getRole()Gets the role of the entity that created this message.List<AbstractToolCall<?, ?>> Filters and returns only the tool call parts from this message.Returns all tool responses associated with the tool calls in this message.booleanChecks if there are any tool calls with responses in a PENDING state.booleanDetermines if this entire batch of tool calls can be executed automatically without user intervention.booleanCalculates the EFFECTIVE pruned state of this message.booleanChecks if this model message is the current tool prompt message for the agi.protected voidonPartPruningStateChanged(AbstractPart part, PruningState oldState, PruningState newState) Lifecycle callback invoked whenever a child part's pruning state changes.voidremove()Removes this message from the agi history.voidremovePart(AbstractPart part) Removes a part from this message and severs the bidirectional link.voidsetBilledCompletionTokens(int billedCompletionTokens) Sets the billed completion token count and fires a property change event.voidsetBilledPromptTokens(int billedPromptTokens) Sets the billed prompt token count and fires a property change event.voidsetFinishReason(FinishReason finishReason) Sets the finish reason and fires a property change event.voidsetGroundingMetadata(GroundingMetadata groundingMetadata) Sets the grounding metadata and fires a property change event.voidsetRawJson(String rawJson) Sets the raw JSON representation of the model's response and fires a property change event.voidSignals the sequential tool execution on this message to halt after the currently executing tool finishes, leaving any subsequent unstarted tools in PENDING state.Methods inherited from class AbstractMessage
addPart, asText, createMetadataHeader, getDepth, getEffectiveTokenCount, getIdentityLabel, getParts, getParts, getRemainingDepth, getTokenCount, isAllPinned, isAllPruned, isAnyPinned, isEmpty, isGarbageCollectable, isPrunnableOrRemovable, pinAllParts, pruneAllParts, resetTokenCounts, setAutoAllParts, shouldCreateMetadataModifier and TypeMethodDescriptionvoidaddPart(@NonNull AbstractPart part) Safely adds a single part to this message, establishing the bidirectional relationship and ensuring the part is fully initialized before firing property change events.asText(boolean includePruned) Convenience method to get the message content as a single string, concatenating the text representation of all its parts.Creates a standardized text header containing metadata for this message.intgetDepth()Calculates the "depth" of this message, defined as its distance from the most recent message in the agi history.intCalculates the total effective tokens consumed by this message, including the in-band metadata header and all of its parts.protected StringReturns the identity label for the metadata header (e.g., "Message ID: 12").getParts()Gets an unmodifiable list of all parts in this message.getParts(boolean includePruned) The definitive, encapsulated method for retrieving the parts of a message that should be sent to the model, respecting the pruning policy.intCalculates the remaining depth of the message as the maximum remaining depth of all its parts.intgetTokenCount(boolean includePruned) Calculates the total number of tokens in this message, summing the token counts of its visible parts.booleanChecks if all parts in this message are explicitly pinned.booleanChecks if all parts in this message are explicitly pruned.booleanChecks if any part in this message is explicitly pinned.booleanisEmpty()Checks if the message is empty.booleanDetermines if this message is eligible for "hard pruning" (permanent removal from history).booleanChecks if this message is eligible for pruning or removal.voidPins all parts in this message.voidExplicitly prunes all parts in this message.voidResets the cached token counts on all parts contained within this message, forcing a lazy recalculation under the new selected model's tokenizer.voidSets all parts in this message to AUTO.booleanHook for subclasses to declare if they should generate in-band metadata headers.Methods inherited from class BasicPropertyChangeSource
addPropertyChangeListener, addPropertyChangeListener, rebind, removePropertyChangeListener, removePropertyChangeListenerModifier and TypeMethodDescriptionvoidAdds a property change listener.voidaddPropertyChangeListener(String propertyName, PropertyChangeListener listener) Adds a property change listener for a specific property.voidrebind()Re-initializes the transientPropertyChangeSupportafter deserialization.voidRemoves a property change listener.voidremovePropertyChangeListener(String propertyName, PropertyChangeListener listener) Removes a property change listener for a specific property.Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface PropertyChangeSource
getPropertyChangeSupportModifier and TypeMethodDescriptionGets the PropertyChangeSupport instance for this object.
-
Field Details
-
providerId
If an AI provider produced this part and assigned an Id to it (e.g. an openai message id). -
providerUuid
The UUID of the AbstractAiProvider that generated this message. -
modelId
The ID of the AbstractModel that generated this message. -
finishReason
The reason why the model stopped generating content for this candidate. -
finishMessage
The message explaining why the model stopped generating content for this candidate. -
groundingMetadata
The grounding metadata for the response. -
safetyRatings
The safety ratings for the response, summarized as a string. -
billedPromptTokens
private int billedPromptTokensThe number of billed prompt (input) tokens for this candidate, as reported by the API. -
billedCompletionTokens
private int billedCompletionTokensThe number of billed completion (output) tokens for this candidate, as reported by the API. -
rawJson
The raw JSON response from the model. -
citationMetadata
The citation metadata for the response, summarized as a string. -
response
-
streaming
private boolean streamingWhether the model is currently streaming content for this message. -
runningAllPending
private volatile boolean runningAllPendingWhether a batch execution of all pending tools is actively underway on this message. -
turnAttributes
A turn scoped map for tools to store turn-scoped attributes.
-
-
Constructor Details
-
AbstractModelMessage
-
-
Method Details
-
getRole
Gets the role of the entity that created this message. This is implemented by subclasses to provide compile-time type safety.- Specified by:
getRolein classAbstractMessage- Returns:
- The role of the message creator.
-
getFrom
Gets the identity of the sender of this message. For user messages, this is typically the user's name. For model messages, it's the model ID. For tool messages, it's the identity of the execution context.- Specified by:
getFromin classAbstractMessage- Returns:
- The sender's identity.
-
getDevice
Gets the ID of the device where this message was created or processed. This could be a hostname, a JVM ID, or a cloud identifier.- Specified by:
getDevicein classAbstractMessage- Returns:
- The device ID.
-
setRawJson
Sets the raw JSON representation of the model's response and fires a property change event. This method replaces any existing content.- Parameters:
rawJson- The raw JSON string.
-
appendRawJson
Appends a raw JSON chunk to the existing content. If multiple chunks are appended, they are automatically wrapped in a JSON array to maintain validity for pretty-printing.- Parameters:
chunk- The JSON chunk to append.
-
setBilledPromptTokens
public void setBilledPromptTokens(int billedPromptTokens) Sets the billed prompt token count and fires a property change event.- Parameters:
billedPromptTokens- The new billed prompt token count.
-
setBilledCompletionTokens
public void setBilledCompletionTokens(int billedCompletionTokens) Sets the billed completion token count and fires a property change event.- Parameters:
billedCompletionTokens- The new billed completion token count.
-
setFinishReason
Sets the finish reason and fires a property change event.- Parameters:
finishReason- The new finish reason.
-
setGroundingMetadata
Sets the grounding metadata and fires a property change event.- Parameters:
groundingMetadata- The new grounding metadata.
-
isEffectivelyPruned
public boolean isEffectivelyPruned()Calculates the EFFECTIVE pruned state of this message. A message is effectively pruned ONLY if it contains no visible (un-pruned) parts. A model message is never effectively pruned while it is streaming.- Overrides:
isEffectivelyPrunedin classAbstractMessage- Returns:
trueif the message is effectively pruned.
-
isToolPromptMessage
public boolean isToolPromptMessage()Checks if this model message is the current tool prompt message for the agi.- Returns:
trueif this message is the tool prompt message.
-
removePart
Removes a part from this message and severs the bidirectional link.Checks tool prompt completion after a part removal.
- Overrides:
removePartin classAbstractMessage- Parameters:
part- The part to remove.
-
remove
public void remove()Removes this message from the agi history.Halts any active batch execution of pending tools before removing the message from history and re-evaluating tool prompt completion.
- Overrides:
removein classAbstractMessage
-
onPartPruningStateChanged
protected void onPartPruningStateChanged(AbstractPart part, PruningState oldState, PruningState newState) Lifecycle callback invoked whenever a child part's pruning state changes. Subclasses can override to propagate reactive updates.Reacts to pruning state changes on tool calls, broadcasting remainingTools updates and re-evaluating tool prompt completion.
- Overrides:
onPartPruningStateChangedin classAbstractMessage- Parameters:
part- The part whose pruning state changed.oldState- The previous pruning state.newState- The new pruning state.
-
getToolCalls
Filters and returns only the tool call parts from this message.- Returns:
- A list of
AbstractToolCallparts, or an empty list if none exist.
-
getPendingToolCalls
Filters and returns all tool calls belonging to this model message that are currently awaiting execution inToolExecutionStatus.PENDINGstate.This method acts as the authoritative domain selector for batch tool dispatching, UI pending counter badges, and human-in-the-loop review actions.
- Returns:
- a list of pending
AbstractToolCallinstances in this message.
-
getRemainingToolCallsCount
public int getRemainingToolCallsCount()Calculates the number of tool calls in this message that are currently active in the execution queue (either actively EXECUTING or still PENDING).- Returns:
- The count of remaining tools in the execution pipeline.
-
getToolResponses
Returns all tool responses associated with the tool calls in this message.- Returns:
- A list of tool responses.
-
isAutoRunnable
public boolean isAutoRunnable()Determines if this entire batch of tool calls can be executed automatically without user intervention.- Returns:
trueif all conditions for automatic execution are met.
-
hasPendingTools
public boolean hasPendingTools()Checks if there are any tool calls with responses in a PENDING state.- Returns:
trueif at least one tool is pending.
-
executeAllPending
public boolean executeAllPending()Executes all tool calls in this message that are currently in a PENDING state, sequentially checking runningAllPending before starting each tool call. Broadcasts remainingTools count updates for live countdown UI display and automatically collapses successfully executed tools.- Returns:
- true if all pending tool calls were executed, false if execution was stopped early and tools remain pending.
-
stopRunningAllPending
public void stopRunningAllPending()Signals the sequential tool execution on this message to halt after the currently executing tool finishes, leaving any subsequent unstarted tools in PENDING state. -
declineAllPending
public void declineAllPending()Sets all tool calls in this message that are currently in a PENDING state to DECLINED and collapses them. -
addTextPart
Creates and adds a new text part to this message. Creates and adds aModelTextPartwithout thought metadata.- Specified by:
addTextPartin classAbstractMessage- Parameters:
text- The text content.- Returns:
- The created text part.
-
addBlobPart
Creates and adds a new binary data part to this message. Creates and adds aModelBlobPartwithout thought metadata.- Specified by:
addBlobPartin classAbstractMessage- Parameters:
mimeType- The MIME type.data- The binary data.- Returns:
- The created blob part.
-
addBlobPart
Creates and adds a new binary data part from a local file path. Creates and adds aModelBlobPartfrom a file path, without thought metadata.- Specified by:
addBlobPartin classAbstractMessage- Parameters:
path- The path to the file.- Returns:
- The created blob part.
- Throws:
Exception- if the file cannot be read or the MIME type cannot be detected.
-
addTextPart
Creates and adds a new model text part with thought process metadata.- Parameters:
text- The text content.thoughtSignature- The thought signature.thought- Whether this is a thought part.- Returns:
- The created model text part.
-
addBlobPart
Creates and adds a new model blob part with thought process metadata.- Parameters:
mimeType- The MIME type.data- The binary data.thoughtSignature- The thought signature.- Returns:
- The created model blob part.
-
appendMetadata
Hook for subclasses to inject specialized metadata into the message header.- Overrides:
appendMetadatain classAbstractMessage- Parameters:
sb- The StringBuilder building the header.
-

