Skip to main content

Messages and Events

AgentForge separates "what the model said" from "what the Agent is doing" into two models:

  • Message: data structures that enter the model context and determine what the next reasoning round sees;
  • Event: incremental updates and state changes during execution that determine how a UI renders in real time.

Both share the same standard response model, so synchronous and streaming execution eventually converge on a consistent context.

Dependency (v1.0.0)​

<dependency>
<groupId>cloud.changlu.agentforge</groupId>
<artifactId>agentforge-agent-core</artifactId>
<version>1.0.2-SNAPSHOT</version>
</dependency>

Message and response contracts live in agentforge-model-api, which is transitively included by agentforge-agent-core. To use them alone:

<dependency>
<groupId>cloud.changlu.agentforge</groupId>
<artifactId>agentforge-model-api</artifactId>
<version>1.0.2-SNAPSHOT</version>
</dependency>

1. Message types​

public interface ChatMessage {
ChatMessageType type();
default String text() { ... }
}
TypePurposeKey fields
SystemMessageSystem prompttext
UserMessageUser inputname, contents
AiMessageModel replytext, thinking, toolExecutionRequests
ToolExecutionResultMessageTool resultid, toolName, text, isError
CustomMessageCustom messageAttributes

1.1 SystemMessage​

SystemMessage system = SystemMessage.from("You are a rigorous Java assistant.");

1.2 UserMessage​

UserMessage text = UserMessage.from("Explain the ReAct loop in AgentForge.");

UserMessage withContents = UserMessage.from(
TextContent.from("First context block"),
TextContent.from("Second context block"));

Use text() for plain text and contents() when there are multiple Content items. The current version only provides TextContent; the Content interface is reserved for future multimodal support.

1.3 AiMessage​

AiMessage answer = AiMessage.from("This is the final answer.");

AiMessage withThinking = AiMessage.builder()
.text("Final answer")
.thinking("Analyze the question first, then decide whether to call a tool")
.build();

When the model requests tools:

for (ToolExecutionRequest request : aiMessage.toolExecutionRequests()) {
System.out.println(request.id());
System.out.println(request.name());
System.out.println(request.arguments()); // raw JSON string
}

1.4 Tool results​

ToolExecutionResultMessage result = ToolExecutionResultMessage.builder()
.id("call_001")
.toolName("getWeather")
.text("{\"weather\":\"Sunny\"}")
.isError(false)
.build();

id must match the corresponding ToolExecutionRequest.id(). The model relies on it to pair results with calls.

2. Response model​

All Providers return a standard ChatResponse:

ChatResponse response = chatModel.chat(request);

AiMessage message = response.aiMessage();
TokenUsage usage = response.tokenUsage();
FinishReason reason = response.finishReason();
Map<String, Object> metadata = response.metadata();
FieldDescription
aiMessageNormalized model message
tokenUsageInput, output, total, and cached tokens
finishReasonSTOP, LENGTH, TOOL_EXECUTION, CONTENT_FILTER, OTHER
metadataProvider extras; business code should not depend on them

3. Model streaming events​

StreamingChatResponseHandler defines the minimum event set at the model layer:

streamingChatModel.chat(request, new StreamingChatResponseHandler() {
@Override
public void onPartialThinking(String partialThinking) {
// Reasoning delta, optional
}

@Override
public void onPartialResponse(String partialResponse) {
// Visible text delta
}

@Override
public void onCompleteResponse(ChatResponse completeResponse) {
// Aggregated standard response, exactly once
}

@Override
public void onError(Throwable error) {
// Failure, exactly once
}
});

Event order:

onPartialThinking* → onPartialResponse* → onCompleteResponse
↘ onError

onCompleteResponse and onError are mutually exclusive.

4. Agent streaming events​

TokenStream adds tool execution and "next round" semantics on top of model events:

agent.runStream(request)
.onPartialThinking(thinking -> { })
.onPartialResponse(token -> { })
.onToolExecuted(execution -> { })
.onIntermediateResponse(response -> { })
.onCompleteResponse(response -> { })
.onError(error -> { })
.start();
EventMeaningSuggested UI behavior
onPartialThinkingReasoning deltaShow a "thinking" collapsible section
onPartialResponseFinal answer text deltaRender Markdown progressively
onToolExecutedOne tool finishedUpdate the tool card status and result
onIntermediateResponseThis round's tools finished, next round is startingKeep tool cards and start new reasoning
onCompleteResponseThe entire ReAct loop finishedStop loading and persist the final answer
onErrorFailure or cancellationShow an error and offer retry

Typical event order with tool calls:

onPartialThinking("Need weather data")
onPartialResponse("Let me check the weather in Beijing.")
onIntermediateResponse(aiMessage.toolCalls = [getWeather])
onToolExecuted(getWeather -> Sunny, 26C)
onPartialResponse("Beijing is sunny today, 26C.")
onCompleteResponse(finalResponse)

Events in middleware​

Register IStreamingIAgentMiddleware to process events before they reach business code:

public class EventMirror implements IStreamingIAgentMiddleware {

@Override
public void onPartialResponse(
int currentStep, String partialResponse, AgentChatContext chatContext) {
// Forward to WebSocket / SSE / logs
}

@Override
public void onIntermediateResponse(
int currentStep, ChatResponse response, AgentChatContext chatContext) {
// Record tool-call rounds
}
}

5. How messages and events cooperate​

User Question
│
▼
UserMessage ──────────────► ChatMemory
│
▼
ChatRequest
│
▼
ChatModel / StreamingChatModel
│
┌─────────────────┴─────────────────┐
│ Synchronous │ Streaming
▼ ▼
ChatResponse partial / complete events
│ │
▼ ▼
AiMessage ───────────────► ChatMemory (next input)
│
▼
ToolExecutionRequest → ToolExecutionResultMessage → ChatMemory

Key point: events describe the process; messages describe the context. Events do not have to be persisted, but the final AiMessage and ToolExecutionResultMessage must be written back to memory, otherwise the next round loses context.

6. Service SSE events​

AgentForge Service defines an SSE protocol on top of SDK events for frontend chat UIs:

EventMeaning
sessionSession created or restored
thinkReasoning delta
respAnswer text delta
tool_callTool call and result
resp_endCurrent answer finished
errorError

Mapping between SDK and Service events:

StreamingChatResponseHandler.onPartialThinking → think
StreamingChatResponseHandler.onPartialResponse → resp
TokenStream.onToolExecuted → tool_call
TokenStream.onCompleteResponse → resp_end
TokenStream.onError → error

7. Design recommendations​

  1. Events are incremental only: do not resend the full history from onPartialResponse;
  2. Use onCompleteResponse as the source of truth: deltas may be lost on reconnect or render failures;
  3. Include id in tool events: pair calls and results with ToolExecutionRequest.id();
  4. Separate reasoning from the answer: thinking must not be mixed into the final response;
  5. Handle errors once: if onError is registered, do not rethrow the same error outside.

Next: use Middleware to process these events consistently.