Class OpenAiModelMessage
java.lang.Object
uno.anahata.asi.agi.event.BasicPropertyChangeSource
uno.anahata.asi.agi.message.AbstractMessage
uno.anahata.asi.agi.message.AbstractModelMessage<OpenAiResponse>
uno.anahata.asi.openai.OpenAiModelMessage
- All Implemented Interfaces:
PropertyChangeSource, Rebindable
Specialized ModelMessage for the OpenAI Responses API.
Aggregates multiple items (messages, reasoning, function calls, web searches, and code execution) from a single Responses API turn into a unified Anahata message. It handles complex multi-item merging and multimodal data harvesting.
- Author:
- anahata
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final com.fasterxml.jackson.databind.ObjectMapperInternal Jackson mapper for stream event processing.static final StringPlaceholder text used for reasoning items in stateless mode when no summary is available.private ModelTextPartTransient tracker for the most recently parsed reasoning item.private StringThe generation phase reported by the model (e.g., 'commentary', 'final_answer').private final Map<AbstractToolCall<?, ?>, ModelTextPart> Tracks the association between tool calls and their parent reasoning chains.Fields inherited from class BasicPropertyChangeSource
propertyChangeSupportModifier and TypeFieldDescriptionprotected PropertyChangeSupportSupport for firing property change events. -
Constructor Summary
ConstructorsConstructorDescriptionOpenAiModelMessage(Agi agi, String modelId) Constructs a new OpenAiModelMessage bound to a specific session and model. -
Method Summary
Modifier and TypeMethodDescriptionvoidappendContent(String text) Appends text to the current active text part or creates a new one if needed.voidappendThoughts(String text) Appends text to the current active reasoning part or creates a new thought part if needed.Gets the ID of the device where this message was created or processed.getFrom()Gets the identity of the sender of this message.voidhandleStreamEvent(com.fasterxml.jackson.databind.JsonNode eventNode) Handles a Server-Sent Event (SSE) from the OpenAI Responses API stream.private voidprocessCitations(com.fasterxml.jackson.databind.JsonNode annotations) Extracts citations from OpenAI annotations and updates the grounding metadata.voidprocessItem(com.fasterxml.jackson.databind.JsonNode item) Processes a single item from the OpenAI 'output' array and maps it to the appropriate Anahata parts.private voidupdateGroundingMetadata(List<String> queries, List<String> texts, List<GroundingSource> sources, String html, String rawJson) Aggregates new metadata components into the message's GroundingMetadata.Methods inherited from class AbstractModelMessage
addBlobPart, addBlobPart, addBlobPart, addTextPart, addTextPart, appendMetadata, appendRawJson, declineAllPending, executeAllPending, getRole, getToolCalls, getToolResponses, hasPendingTools, isAutoRunnable, isEffectivelyPruned, isToolPromptMessage, processPendingTools, remove, removePart, setBilledCompletionTokens, setBilledPromptTokens, setFinishReason, setGroundingMetadata, setRawJsonModifier 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.voidExecutes all tool calls in this message that are currently in a PENDING state.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.voidProcesses all tool responses associated with this message that are currently in a PENDING state.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.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
-
API_MAPPER
private static final com.fasterxml.jackson.databind.ObjectMapper API_MAPPERInternal Jackson mapper for stream event processing. -
ENCRYPTED_REASONING_PLACEHOLDER
Placeholder text used for reasoning items in stateless mode when no summary is available.- See Also:
-
phase
The generation phase reported by the model (e.g., 'commentary', 'final_answer'). -
toolThoughts
Tracks the association between tool calls and their parent reasoning chains. This is required for OpenAI's strict referential integrity. -
lastParsedThought
Transient tracker for the most recently parsed reasoning item.
-
-
Constructor Details
-
OpenAiModelMessage
-
-
Method Details
-
processItem
public void processItem(com.fasterxml.jackson.databind.JsonNode item) Processes a single item from the OpenAI 'output' array and maps it to the appropriate Anahata parts.This includes handling messages, reasoning chains, function calls, web searches, and code interpreter executions.
- Parameters:
item- The JSON node representing an OpenAI item.
-
processCitations
private void processCitations(com.fasterxml.jackson.databind.JsonNode annotations) Extracts citations from OpenAI annotations and updates the grounding metadata.- Parameters:
annotations- The JSON array of annotations from the API.
-
updateGroundingMetadata
private void updateGroundingMetadata(List<String> queries, List<String> texts, List<GroundingSource> sources, String html, String rawJson) Aggregates new metadata components into the message's GroundingMetadata.Ensures that citations, supporting texts, and search queries from multiple items are correctly merged and deduped.
- Parameters:
queries- Suggested search queries.texts- Supporting text segments.sources- Grounding sources (citations).html- The search entry point HTML.rawJson- The raw JSON from the provider.
-
handleStreamEvent
public void handleStreamEvent(com.fasterxml.jackson.databind.JsonNode eventNode) Handles a Server-Sent Event (SSE) from the OpenAI Responses API stream.Routes deltas for real-time text and reasoning generation, and defers complex items (function calls, web searches) to the completion of the item where the full JSON structure is guaranteed to be intact.
- Parameters:
eventNode- The parsed JSON node of the stream event.
-
appendContent
Appends text to the current active text part or creates a new one if needed.- Parameters:
text- The text delta to append.
-
appendThoughts
Appends text to the current active reasoning part or creates a new thought part if needed.- Parameters:
text- The reasoning delta to append.
-
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.- Overrides:
getFromin classAbstractModelMessage<OpenAiResponse>- 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.- Overrides:
getDevicein classAbstractModelMessage<OpenAiResponse>- Returns:
- The device ID.
-

