Class DefaultAgenticScope
java.lang.Object
dev.langchain4j.agentic.scope.DefaultAgenticScope
- All Implemented Interfaces:
AgenticScope, LangChain4jManaged
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final recordstatic enum -
Field Summary
Fields inherited from interface LangChain4jManaged
CURRENT -
Method Summary
Modifier and TypeMethodDescriptionstatic voidaddSerializableStateFilter(Predicate<Object> filter) Returns all agent invocations recorded in this scope, in execution order.agentInvocations(Class<?> agentType) Returns all agent invocations for agents of the given type.agentInvocations(String agentName) Returns all agent invocations for the agent with the given name.voidasyncEnded(String outputKey, AsyncResponse<?> response) Completes an asynchronous agent, on the thread of its executor.voidasyncPending(String agentName, String outputKey, AsyncResponse<?> response) Tracks the response of an asynchronous agent just written to this scope: its result takes the place of the response when it completes, seeasyncEnded(String, AsyncResponse), and until then the next root call on this scope waits for it.The agents created for this scope only, bygetOrCreateAgent(String, Function): the AI agents whose configuration depends on the scope, and the planner agent of a supervisor.voidcheckpoint(AgenticScopeRegistry registry) Checkpoints the current state of this scope by persisting it to the store.voidbooleancompletePendingResponse(String responseId, Object value) Completes aDeferredResponsestored in this scope's state.context()contextAsConversation(Object... agents) Returns the conversation context as a human-readable string, optionally filtered by agent instances.contextAsConversation(String... agentNames) Returns the conversation context as a human-readable string, optionally filtered by agent names.static DefaultAgenticScopeexecutionContext(String key) Retrieves non-serializable execution context from this scope by key.<T> TexecutionContextAs(String key, Class<T> type) Retrieves non-serializable execution context from this scope by key with type-safe casting.<T> TgetOrCreateAgent(String agentId, Function<DefaultAgenticScope, T> agentFactory) handleError(String agentName, AgentInvocationException exception) booleanChecks whether the shared state contains a non-blank value for the given typed key.booleanChecks whether the shared state contains a non-blank value for the given key.static booleanisSerializable(Object value) memoryId()Returns the unique memory identifier for this scope.Returns the identifiers of allDeferredResponseinstances stored in this scope's state that have not yet been completed.<T> TReads the value associated with the given typed key from the shared state.Reads the value associated with the given key from the shared state.<T> TReads the value associated with the given key from the shared state, returning a default value if the key is not present.voidregisterAgentInvocation(AgentInvocation agentInvocation) voidregisterCompensableExecution(ToolExecution toolExecution, Consumer<ToolExecution> compensatingAction) voidregisterContext(AgentInstance agent, Object agentObject, UserMessage userMessage, Object output) Adds to the context of this scope the messages exchanged by an AI agent in the invocation that just completed: the last user message and the last answer of its chat memory when it has one, otherwise the user message of its last model call, when known, and its output.voidrootCallEnded(AgenticScopeRegistry registry, AgentListener agentListener, boolean failed) Ends the root call, whichfailedtells whether it ended with an exception.voidrootCallStarted(AgenticScopeRegistry registry) Starts a root call, once the asynchronous agents of the previous call on this scope still running completed: one root call at a time runs on a scope, since those agents would otherwise share with the new call the chat memory of their agents, the context and the compensations of the scope and the execution recorded by anAgentMonitor.voidrootCallSuspended(AgenticScopeRegistry registry, AgentListener agentListener) Suspends the root call, which returns to its caller to be resumed by a later call on this scope, and notifies the listener of the suspension.The state that is safe to persist.state()Returns a live view of the entire shared state map.toString()withErrorHandler(Function<ErrorContext, ErrorRecoveryResult> errorHandler) voidwriteExecutionContext(String key, Object context) Stores non-serializable execution context in this scope, keyed by name.<T> voidwriteState(Class<? extends TypedKey<T>> key, T value) Writes a value into the shared state using a strongly typed key.voidwriteState(String key, Object value) Writes a value into the shared state under the given key.<T> voidwriteStateIfAbsent(Class<? extends TypedKey<T>> key, T value) Writes a value into the shared state using a strongly typed key only if the key is not already considered present byAgenticScope.hasState(Class).voidwriteStateIfAbsent(String key, Object value) Writes a value into the shared state under the given key only if the key is not already considered present byAgenticScope.hasState(String).voidwriteStates(Map<String, Object> newState) Writes multiple key-value pairs into the shared state at once.Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface AgenticScope
completePendingResponse, executionContextAs, writeExecutionContext
-
Method Details
-
serializableCopy
The state that is safe to persist. Public so that a JSON codec supplied through the SPI can reach it from another package. -
isSerializable
-
addSerializableStateFilter
-
ephemeralAgenticScope
-
memoryId
Description copied from interface:AgenticScopeReturns the unique memory identifier for this scope. This ID is used to associate the scope with a specific conversation or session, and to look up persisted scopes from a store.- Specified by:
memoryIdin interfaceAgenticScope- Returns:
- the memory identifier
-
writeState
Description copied from interface:AgenticScopeWrites a value into the shared state under the given key. If the value isnull, the key is removed from the state.- Specified by:
writeStatein interfaceAgenticScope- Parameters:
key- the state keyvalue- the value to store, ornullto remove the key
-
writeState
Description copied from interface:AgenticScopeWrites a value into the shared state using a strongly typed key. The key's name is derived from theTypedKeyclass.- Specified by:
writeStatein interfaceAgenticScope- Type Parameters:
T- the type of the value- Parameters:
key- the typed key classvalue- the value to store
-
writeStateIfAbsent
Description copied from interface:AgenticScopeWrites a value into the shared state under the given key only if the key is not already considered present byAgenticScope.hasState(String). A key is considered absent when it has no mapping, or its value is a blank string — so this method will overwrite a previously stored blank string.If
valueisnullthe call is a no-op (unlikeAgenticScope.writeState(String, Object), which removes the key onnull).- Specified by:
writeStateIfAbsentin interfaceAgenticScope- Parameters:
key- the state keyvalue- the value to store, ornullfor no-op
-
writeStateIfAbsent
Description copied from interface:AgenticScopeWrites a value into the shared state using a strongly typed key only if the key is not already considered present byAgenticScope.hasState(Class). SeeAgenticScope.writeStateIfAbsent(String, Object)for the full absence/blank-string semantics.- Specified by:
writeStateIfAbsentin interfaceAgenticScope- Type Parameters:
T- the type of the value- Parameters:
key- the typed key classvalue- the value to store, ornullfor no-op
-
writeStates
Description copied from interface:AgenticScopeWrites multiple key-value pairs into the shared state at once.- Specified by:
writeStatesin interfaceAgenticScope- Parameters:
newState- a map of key-value pairs to store
-
hasState
Description copied from interface:AgenticScopeChecks whether the shared state contains a non-blank value for the given key.- Specified by:
hasStatein interfaceAgenticScope- Parameters:
key- the state key- Returns:
trueif the key exists and its value is non-null (and non-blank for strings)
-
hasState
Description copied from interface:AgenticScopeChecks whether the shared state contains a non-blank value for the given typed key.- Specified by:
hasStatein interfaceAgenticScope- Parameters:
key- the typed key class- Returns:
trueif the key exists and its value is non-null (and non-blank for strings)
-
readState
Description copied from interface:AgenticScopeReads the value associated with the given key from the shared state. If the value is aDelayedResponse, this method blocks until the response is available.- Specified by:
readStatein interfaceAgenticScope- Parameters:
key- the state key- Returns:
- the value, or
nullif the key is not present
-
readState
Description copied from interface:AgenticScopeReads the value associated with the given key from the shared state, returning a default value if the key is not present. If the value is aDelayedResponse, this method blocks until the response is available.- Specified by:
readStatein interfaceAgenticScope- Type Parameters:
T- the type of the value- Parameters:
key- the state keydefaultValue- the value to return if the key is not present- Returns:
- the value, or
defaultValueif the key is not present
-
readState
Description copied from interface:AgenticScopeReads the value associated with the given typed key from the shared state. The key's name and default value are derived from theTypedKeyclass. If the value is aDelayedResponse, this method blocks until the response is available.- Specified by:
readStatein interfaceAgenticScope- Type Parameters:
T- the type of the value- Parameters:
key- the typed key class- Returns:
- the value, or the key's default value if not present
-
state
Description copied from interface:AgenticScopeReturns a live view of the entire shared state map. Modifications to this map are reflected in the scope's state.- Specified by:
statein interfaceAgenticScope- Returns:
- the mutable state map
-
getOrCreateAgent
-
cachedAgents
The agents created for this scope only, bygetOrCreateAgent(String, Function): the AI agents whose configuration depends on the scope, and the planner agent of a supervisor. They are not part of the agent tree of the agentic system, so they have to be reached through the scope, for instance to evict their chat memories. -
registerAgentInvocation
-
registerContext
public void registerContext(AgentInstance agent, Object agentObject, UserMessage userMessage, Object output) Adds to the context of this scope the messages exchanged by an AI agent in the invocation that just completed: the last user message and the last answer of its chat memory when it has one, otherwise the user message of its last model call, when known, and its output. Other kinds of agents have no messages to add. -
rootCallStarted
Starts a root call, once the asynchronous agents of the previous call on this scope still running completed: one root call at a time runs on a scope, since those agents would otherwise share with the new call the chat memory of their agents, the context and the compensations of the scope and the execution recorded by anAgentMonitor. The tool executions of the agents completed after the end of the previous call are then dropped, as those of a completed root call are: a failure of this call does not compensate them. The failed responses of those agents are dropped too, as the saved copy of a persistent scope never contains them: their failure was reported, and an agent of this call must not fail for it, like a skipped agent returning the current value of its output key would. -
rootCallSuspended
Suspends the root call, which returns to its caller to be resumed by a later call on this scope, and notifies the listener of the suspension. As after a completed call, the failure of an asynchronous agent completing afterwards is reported, and a persistent scope is saved again with its result. The suspension of an asynchronous agent is reported only when the scope then has a pending response that was not pending yet when the root call notified its suspension: an agent leaves its pending response just before it completes, so the root call may have suspended on it, and notified it, while the agent was still running. The pending responses are taken before notifying, so that one left while the listener runs is notified again rather than never. -
rootCallEnded
public void rootCallEnded(AgenticScopeRegistry registry, AgentListener agentListener, boolean failed) Ends the root call, whichfailedtells whether it ended with an exception. The responses of the asynchronous agents that no agent of the root call read are left in place, and the root call does not wait for them: their failure is logged on completion when the call succeeded, since no agent would observe it otherwise, while a failed root call already surfaced the failure of the response it read, and a suspension of the agentic system by one of them, which the call returned without noticing, is notified to the listener. -
asyncPending
Tracks the response of an asynchronous agent just written to this scope: its result takes the place of the response when it completes, seeasyncEnded(String, AsyncResponse), and until then the next root call on this scope waits for it. Called after the write, so that the result of an agent completing before it is settled anyway. -
asyncEnded
Completes an asynchronous agent, on the thread of its executor. Its result replaces the response under its output key, if the key still holds that response, as reading it would have done, while a failure is left in place, so that reading it still fails, until the next root call on this scope drops it. A persistent scope whose root call already ended is then saved again, with the result. -
context
-
contextAsConversation
Description copied from interface:AgenticScopeReturns the conversation context as a human-readable string, optionally filtered by agent instances. Each entry shows the user message and the agent's response.- Specified by:
contextAsConversationin interfaceAgenticScope- Parameters:
agents- the agent instances to include; if empty, all agents are included- Returns:
- the conversation context as a formatted string
-
contextAsConversation
Description copied from interface:AgenticScopeReturns the conversation context as a human-readable string, optionally filtered by agent names. Each entry shows the user message and the agent's response.- Specified by:
contextAsConversationin interfaceAgenticScope- Parameters:
agentNames- the names of the agents to include; if empty, all agents are included- Returns:
- the conversation context as a formatted string
-
agentInvocations
Description copied from interface:AgenticScopeReturns all agent invocations recorded in this scope, in execution order.- Specified by:
agentInvocationsin interfaceAgenticScope- Returns:
- an unmodifiable list of all agent invocations
-
agentInvocations
Description copied from interface:AgenticScopeReturns all agent invocations for the agent with the given name.- Specified by:
agentInvocationsin interfaceAgenticScope- Parameters:
agentName- the name of the agent- Returns:
- a list of invocations matching the agent name
-
agentInvocations
Description copied from interface:AgenticScopeReturns all agent invocations for agents of the given type.- Specified by:
agentInvocationsin interfaceAgenticScope- Parameters:
agentType- the class of the agent- Returns:
- a list of invocations matching the agent type
-
toString
-
withErrorHandler
public DefaultAgenticScope withErrorHandler(Function<ErrorContext, ErrorRecoveryResult> errorHandler) -
handleError
-
registerCompensableExecution
public void registerCompensableExecution(ToolExecution toolExecution, Consumer<ToolExecution> compensatingAction) -
compensateAll
public void compensateAll() -
checkpoint
Checkpoints the current state of this scope by persisting it to the store. This is a no-op for non-persistent scopes. For persistent scopes, it acquires the write lock and flushes the current state to the store.- Parameters:
registry- the registry managing this scope's persistence
-
completePendingResponse
Description copied from interface:AgenticScopeCompletes aDeferredResponsestored in this scope's state. This is typically called by an external system (e.g., a REST endpoint) to provide a human's response after a process restart or when using a polling/event-driven model.- Specified by:
completePendingResponsein interfaceAgenticScope- Parameters:
responseId- the unique identifier of the pending responsevalue- the value to complete the response with, ornullto complete it with no value, which removes the key from the state asAgenticScope.writeState(String, Object)does- Returns:
trueif a matching pending response was found and completed
-
pendingResponseIds
Description copied from interface:AgenticScopeReturns the identifiers of allDeferredResponseinstances stored in this scope's state that have not yet been completed.- Specified by:
pendingResponseIdsin interfaceAgenticScope- Returns:
- a set of pending response identifiers
-
writeExecutionContext
Description copied from interface:AgenticScopeStores non-serializable execution context in this scope, keyed by name.This allows custom
Plannerimplementations to store runtime objects that are needed during execution but should not be persisted. The execution context is stored in atransientmap and will not be serialized.This is distinct from
AgenticScope.writeState(String, Object), which is for serializable agent interaction data that forms part of the conversation state.- Specified by:
writeExecutionContextin interfaceAgenticScope- Parameters:
key- the key to use for this context (must not benull)context- the execution context instance to store (must not benull)
-
executionContext
Description copied from interface:AgenticScopeRetrieves non-serializable execution context from this scope by key.Returns execution context previously stored via
AgenticScope.writeExecutionContext(String, Object).- Specified by:
executionContextin interfaceAgenticScope- Parameters:
key- the key used to store the execution context- Returns:
- the execution context instance previously stored for this key, or
nullif none exists
-
executionContextAs
Description copied from interface:AgenticScopeRetrieves non-serializable execution context from this scope by key with type-safe casting.Returns execution context previously stored via
AgenticScope.writeExecutionContext(String, Object).- Specified by:
executionContextAsin interfaceAgenticScope- Type Parameters:
T- the type of the execution context- Parameters:
key- the key used to store the execution contexttype- the expected type of the execution context (for type-safe casting)- Returns:
- the execution context instance previously stored for this key, or
nullif none exists
-