类 AgentBase
- 所有已实现的接口:
Agent,CallableAgent,ObservableAgent,StreamableAgent,StateModule
- 直接已知子类:
StructuredOutputCapableAgent,UserAgent
This class provides common functionality for agents including basic hook integration, MsgHub subscriber management, interrupt handling, tracing, and state management through StateModule. It does NOT manage memory - that is the responsibility of specific agent implementations like ReActAgent.
Design Philosophy:
- AgentBase provides infrastructure (hooks, subscriptions, interrupt, state) but not domain logic
- Memory management is delegated to concrete agents that need it (e.g., ReActAgent)
- State management implements StateModule interface
- Interrupt mechanism uses reactive patterns: subclasses call checkInterruptedAsync() at appropriate checkpoints, which propagates InterruptedException through Mono chain
- Observe pattern: agents can receive messages without generating a reply
Thread Safety:
Agent instances are NOT designed for concurrent execution. A single agent instance should not
be invoked concurrently from multiple threads (e.g., calling call() or stream()
simultaneously). The hooks list is mutable and modified during streaming operations without
synchronization, which is safe only under single-threaded execution per agent instance.
Interrupt Mechanism:
// External call to interrupt
agent.interrupt(userMsg);
// Inside agent's Mono chain, at checkpoints:
return checkInterruptedAsync()
.then(doWork())
.flatMap(result -> checkInterruptedAsync().thenReturn(result));
// AgentBase.call() catches the exception:
.onErrorResume(error -> {
if (error instanceof InterruptedException) {
return handleInterrupt(context, msg);
}
...
});
-
构造器概要
构造器 -
方法概要
修饰符和类型方法说明protected voidAdd a hook to this agent dynamically.static voidaddSystemHook(Hook hook) final reactor.core.publisher.Mono<Msg> Process a list of input messages and generate a response with hook execution.final reactor.core.publisher.Mono<Msg> Process multiple input messages and generate structured output with hook execution.final reactor.core.publisher.Mono<Msg> Process multiple input messages and generate structured output with hook execution.protected reactor.core.publisher.Mono<Void> Check if the agent execution has been interrupted (reactive version).protected abstract reactor.core.publisher.Mono<Msg> Internal implementation for processing multiple input messages.protected reactor.core.publisher.Mono<Msg> Internal implementation for processing multiple messages with structured output.protected reactor.core.publisher.Mono<Msg> Internal implementation for processing multiple messages with structured output.protected reactor.core.publisher.Mono<Void> Observe a message without generating a reply.final StringGet the unique identifier for this agent.final StringGet the description of this agent.getHooks()Get the list of hooks for this agent.protected AtomicBooleanGet the interrupt flag for access by subclasses.protected InterruptSourceGet current interruption source.final StringgetName()Get the name of this agent.Get hooks sorted by priority (lower value = higher priority).intGet the total number of subscribers across all MsgHubs.protected abstract reactor.core.publisher.Mono<Msg> handleInterrupt(InterruptContext context, Msg... originalArgs) Handle an interruption that occurred during execution.booleanCheck if this agent has any subscribers.voidInterrupt the current agent execution.voidinterrupt(InterruptSource source) Interrupt execution with explicit source.voidInterrupt the current agent execution with a user message.final reactor.core.publisher.Mono<Void> Observe a single message without generating a reply.final reactor.core.publisher.Mono<Void> Observe multiple messages without generating a reply.protected voidremoveHook(Hook hook) Remove a hook from this agent dynamically.voidremoveSubscribers(String hubId) Remove all subscribers for a specific MsgHub.static voidremoveSystemHook(Hook hook) protected voidReset the interrupt flag and associated state.voidresetSubscribers(String hubId, List<AgentBase> subscribers) Reset the subscriber list for a specific MsgHub.final reactor.core.publisher.Flux<Event> stream(List<Msg> msgs, StreamOptions options) Stream with multiple input messages.final reactor.core.publisher.Flux<Event> stream(List<Msg> msgs, StreamOptions options, com.fasterxml.jackson.databind.JsonNode schema) Stream with multiple input messages using a JSON schema.final reactor.core.publisher.Flux<Event> stream(List<Msg> msgs, StreamOptions options, Class<?> structuredModel) Stream with multiple input messages.toString()从类继承的方法 java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait从接口继承的方法 io.agentscope.core.state.StateModule
loadFrom, loadFrom, loadIfExists, loadIfExists, saveTo, saveTo
-
构造器详细资料
-
AgentBase
Constructor for AgentBase.- 参数:
name- Agent name
-
AgentBase
Constructor for AgentBase.- 参数:
name- Agent namedescription- Agent description
-
AgentBase
Constructor for AgentBase with hooks.- 参数:
name- Agent namedescription- Agent descriptioncheckRunning- Whether to check running statehooks- List of hooks for monitoring/intercepting execution
-
-
方法详细资料
-
getAgentId
从接口复制的说明:AgentGet the unique identifier for this agent.- 指定者:
getAgentId在接口中Agent- 返回:
- Agent ID
-
getName
从接口复制的说明:AgentGet the name of this agent. -
getDescription
从接口复制的说明:AgentGet the description of this agent.- 指定者:
getDescription在接口中Agent- 返回:
- Agent description
-
call
Process a list of input messages and generate a response with hook execution.Tracing data will be captured once telemetry is enabled.
- 指定者:
call在接口中CallableAgent- 参数:
msgs- Input messages- 返回:
- Response message
-
call
Process multiple input messages and generate structured output with hook execution.Tracing data will be captured once telemetry is enabled.
- 指定者:
call在接口中CallableAgent- 参数:
msgs- Input messagesstructuredOutputClass- Class defining the structure of the output- 返回:
- Response message with structured data in metadata
-
call
public final reactor.core.publisher.Mono<Msg> call(List<Msg> msgs, com.fasterxml.jackson.databind.JsonNode schema) Process multiple input messages and generate structured output with hook execution.Tracing data will be captured once telemetry is enabled.
- 指定者:
call在接口中CallableAgent- 参数:
msgs- Input messagesschema- com.fasterxml.jackson.databind.JsonNode instance defining the structure of the output- 返回:
- Response message with structured data in metadata
-
doCall
Internal implementation for processing multiple input messages. Subclasses must implement their specific logic here.- 参数:
msgs- Input messages- 返回:
- Response message
-
doCall
Internal implementation for processing multiple messages with structured output. Subclasses that support structured output must override this method. Default implementation throws UnsupportedOperationException.- 参数:
msgs- Input messagesstructuredOutputClass- Class defining the structure- 返回:
- Response message with structured data in metadata
-
doCall
protected reactor.core.publisher.Mono<Msg> doCall(List<Msg> msgs, com.fasterxml.jackson.databind.JsonNode outputSchema) Internal implementation for processing multiple messages with structured output. Subclasses that support structured output must override this method. Default implementation throws UnsupportedOperationException.- 参数:
msgs- Input messagesoutputSchema- com.fasterxml.jackson.databind.JsonNode instance defining the structure- 返回:
- Response message with structured data in metadata
-
addSystemHook
-
removeSystemHook
-
interrupt
public void interrupt()Interrupt the current agent execution. Sets an interrupt flag that will be checked by the agent at appropriate checkpoints. -
interrupt
Interrupt the current agent execution with a user message. Sets an interrupt flag and associates a user message with the interruption. -
interrupt
Interrupt execution with explicit source.- 参数:
source- interruption source
-
checkInterruptedAsync
Check if the agent execution has been interrupted (reactive version). Returns a Mono that completes normally if not interrupted, or errors with InterruptedException if interrupted.Subclasses should call this at appropriate checkpoints in their Mono chains. For simple agents (like UserAgent), checkpoints may not be needed. For complex agents (like ReActAgent), call this at:
- Start of each iteration
- Before/after reasoning
- Before/after each tool execution
- During streaming (each chunk)
Example usage:
return checkInterruptedAsync() .then(reasoning()) .flatMap(result -> checkInterruptedAsync().thenReturn(result)) .flatMap(result -> executeTools(result));- 返回:
- Mono that completes if not interrupted, or errors if interrupted
-
resetInterruptFlag
protected void resetInterruptFlag()Reset the interrupt flag and associated state. This is called at the beginning of each call() to prepare for new execution. -
getInterruptFlag
Get the interrupt flag for access by subclasses. Subclasses can use this flag to implement custom interrupt-checking logic in addition to the standard checkInterruptedAsync() method.- 返回:
- The atomic boolean interrupt flag
-
getInterruptSource
Get current interruption source.- 返回:
- interruption source
-
doObserve
Observe a message without generating a reply. This allows agents to receive messages from other agents or the environment without responding. It's commonly used in multi-agent collaboration scenarios.Common implementation patterns:
- Stateless agents: Empty implementation if observation is not needed
- Stateful agents: Store message in memory/context for use in future calls
- Collaborative agents: Update shared knowledge or trigger side effects
- 参数:
msg- The message to observe- 返回:
- Mono that completes when observation is done
-
handleInterrupt
protected abstract reactor.core.publisher.Mono<Msg> handleInterrupt(InterruptContext context, Msg... originalArgs) Handle an interruption that occurred during execution. Subclasses must implement this to provide recovery logic based on the interrupt context.Implementation guidance:
- Simple agents: Return a basic interrupt acknowledgment message
- Complex agents: Generate a summary including any pending operations or partial results
- Stateful agents: Ensure state is saved appropriately before returning
- 参数:
context- The interrupt context containing metadata about the interruptionoriginalArgs- The original arguments passed to the call() method (empty, single Msg, or List)- 返回:
- Recovery message to return to the user
-
getHooks
Get the list of hooks for this agent. Protected to allow subclasses to access hooks for custom notification logic.- 返回:
- List of hooks
-
addHook
Add a hook to this agent dynamically.Hooks can be added during agent execution to provide temporary functionality. This is commonly used for structured output handling or other short-lived behaviors.
- 参数:
hook- The hook to add
-
removeHook
Remove a hook from this agent dynamically.Hooks should be removed when they are no longer needed to avoid memory leaks and unintended side effects.
- 参数:
hook- The hook to remove
-
getSortedHooks
Get hooks sorted by priority (lower value = higher priority). Hooks with the same priority maintain registration order.- 返回:
- Sorted list of hooks
-
removeSubscribers
Remove all subscribers for a specific MsgHub. This method is typically called when a MsgHub is being destroyed or reset. After calling this method, the agent will no longer receive messages from the specified hub.- 参数:
hubId- MsgHub identifier
-
resetSubscribers
Reset the subscriber list for a specific MsgHub. This replaces any existing subscribers for the given hub with the new list. Typically called by MsgHub when the subscription topology changes.- 参数:
hubId- MsgHub identifiersubscribers- New list of subscribers (will be copied)
-
hasSubscribers
public boolean hasSubscribers()Check if this agent has any subscribers. Subscribers are agents that will receive messages published through MsgHub.- 返回:
- True if agent has one or more subscribers
-
getSubscriberCount
public int getSubscriberCount()Get the total number of subscribers across all MsgHubs. Subscribers are agents that will receive messages published through MsgHub.- 返回:
- Total count of subscribers
-
observe
Observe a single message without generating a reply. This is the public API that delegates to doObserve implementation.- 指定者:
observe在接口中ObservableAgent- 参数:
msg- Message to observe- 返回:
- Mono that completes when observation is done
-
observe
Observe multiple messages without generating a reply. This is the public API that delegates to doObserve implementation.- 指定者:
observe在接口中ObservableAgent- 参数:
msgs- Messages to observe- 返回:
- Mono that completes when all observations are done
-
stream
Stream with multiple input messages.- 指定者:
stream在接口中StreamableAgent- 参数:
msgs- Input messagesoptions- Stream configuration options- 返回:
- Flux of events emitted during execution
-
stream
public final reactor.core.publisher.Flux<Event> stream(List<Msg> msgs, StreamOptions options, Class<?> structuredModel) Stream with multiple input messages.- 指定者:
stream在接口中StreamableAgent- 参数:
msgs- Input messagesoptions- Stream configuration optionsstructuredModel- Optional class defining the structure- 返回:
- Flux of events emitted during execution
-
stream
public final reactor.core.publisher.Flux<Event> stream(List<Msg> msgs, StreamOptions options, com.fasterxml.jackson.databind.JsonNode schema) Stream with multiple input messages using a JSON schema.- 指定者:
stream在接口中StreamableAgent- 参数:
msgs- Input messagesoptions- Stream configuration optionsschema- JSON schema defining the structure of the response- 返回:
- Flux of events emitted during execution
-
toString
-