Class DefaultAgenticScope

java.lang.Object
dev.langchain4j.agentic.scope.DefaultAgenticScope
All Implemented Interfaces:
AgenticScope, LangChain4jManaged

public class DefaultAgenticScope extends Object implements AgenticScope
  • Method Details

    • serializableCopy

      public DefaultAgenticScope 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

      public static boolean isSerializable(Object value)
    • addSerializableStateFilter

      public static void addSerializableStateFilter(Predicate<Object> filter)
    • ephemeralAgenticScope

      public static DefaultAgenticScope ephemeralAgenticScope()
    • memoryId

      public Object memoryId()
      Description copied from interface: AgenticScope
      Returns 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:
      memoryId in interface AgenticScope
      Returns:
      the memory identifier
    • writeState

      public void writeState(String key, Object value)
      Description copied from interface: AgenticScope
      Writes a value into the shared state under the given key. If the value is null, the key is removed from the state.
      Specified by:
      writeState in interface AgenticScope
      Parameters:
      key - the state key
      value - the value to store, or null to remove the key
    • writeState

      public <T> void writeState(Class<? extends TypedKey<T>> key, T value)
      Description copied from interface: AgenticScope
      Writes a value into the shared state using a strongly typed key. The key's name is derived from the TypedKey class.
      Specified by:
      writeState in interface AgenticScope
      Type Parameters:
      T - the type of the value
      Parameters:
      key - the typed key class
      value - the value to store
    • writeStateIfAbsent

      public void writeStateIfAbsent(String key, Object value)
      Description copied from interface: AgenticScope
      Writes a value into the shared state under the given key only if the key is not already considered present by AgenticScope.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 value is null the call is a no-op (unlike AgenticScope.writeState(String, Object), which removes the key on null).

      Specified by:
      writeStateIfAbsent in interface AgenticScope
      Parameters:
      key - the state key
      value - the value to store, or null for no-op
    • writeStateIfAbsent

      public <T> void writeStateIfAbsent(Class<? extends TypedKey<T>> key, T value)
      Description copied from interface: AgenticScope
      Writes a value into the shared state using a strongly typed key only if the key is not already considered present by AgenticScope.hasState(Class). See AgenticScope.writeStateIfAbsent(String, Object) for the full absence/blank-string semantics.
      Specified by:
      writeStateIfAbsent in interface AgenticScope
      Type Parameters:
      T - the type of the value
      Parameters:
      key - the typed key class
      value - the value to store, or null for no-op
    • writeStates

      public void writeStates(Map<String,Object> newState)
      Description copied from interface: AgenticScope
      Writes multiple key-value pairs into the shared state at once.
      Specified by:
      writeStates in interface AgenticScope
      Parameters:
      newState - a map of key-value pairs to store
    • hasState

      public boolean hasState(String key)
      Description copied from interface: AgenticScope
      Checks whether the shared state contains a non-blank value for the given key.
      Specified by:
      hasState in interface AgenticScope
      Parameters:
      key - the state key
      Returns:
      true if the key exists and its value is non-null (and non-blank for strings)
    • hasState

      public boolean hasState(Class<? extends TypedKey<?>> key)
      Description copied from interface: AgenticScope
      Checks whether the shared state contains a non-blank value for the given typed key.
      Specified by:
      hasState in interface AgenticScope
      Parameters:
      key - the typed key class
      Returns:
      true if the key exists and its value is non-null (and non-blank for strings)
    • readState

      public Object readState(String key)
      Description copied from interface: AgenticScope
      Reads the value associated with the given key from the shared state. If the value is a DelayedResponse, this method blocks until the response is available.
      Specified by:
      readState in interface AgenticScope
      Parameters:
      key - the state key
      Returns:
      the value, or null if the key is not present
    • readState

      public <T> T readState(String key, T defaultValue)
      Description copied from interface: AgenticScope
      Reads 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 a DelayedResponse, this method blocks until the response is available.
      Specified by:
      readState in interface AgenticScope
      Type Parameters:
      T - the type of the value
      Parameters:
      key - the state key
      defaultValue - the value to return if the key is not present
      Returns:
      the value, or defaultValue if the key is not present
    • readState

      public <T> T readState(Class<? extends TypedKey<T>> key)
      Description copied from interface: AgenticScope
      Reads the value associated with the given typed key from the shared state. The key's name and default value are derived from the TypedKey class. If the value is a DelayedResponse, this method blocks until the response is available.
      Specified by:
      readState in interface AgenticScope
      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

      public Map<String,Object> state()
      Description copied from interface: AgenticScope
      Returns a live view of the entire shared state map. Modifications to this map are reflected in the scope's state.
      Specified by:
      state in interface AgenticScope
      Returns:
      the mutable state map
    • getOrCreateAgent

      public <T> T getOrCreateAgent(String agentId, Function<DefaultAgenticScope, T> agentFactory)
    • cachedAgents

      public Collection<Object> cachedAgents()
      The agents created for this scope only, by getOrCreateAgent(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

      public void registerAgentInvocation(AgentInvocation agentInvocation)
    • 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

      public void rootCallStarted(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 an AgentMonitor. 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

      public void rootCallSuspended(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. 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, which failed tells 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

      public void asyncPending(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, see asyncEnded(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

      public void asyncEnded(String outputKey, AsyncResponse<?> response)
      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

      public String contextAsConversation(Object... agents)
      Description copied from interface: AgenticScope
      Returns 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:
      contextAsConversation in interface AgenticScope
      Parameters:
      agents - the agent instances to include; if empty, all agents are included
      Returns:
      the conversation context as a formatted string
    • contextAsConversation

      public String contextAsConversation(String... agentNames)
      Description copied from interface: AgenticScope
      Returns 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:
      contextAsConversation in interface AgenticScope
      Parameters:
      agentNames - the names of the agents to include; if empty, all agents are included
      Returns:
      the conversation context as a formatted string
    • agentInvocations

      public List<AgentInvocation> agentInvocations()
      Description copied from interface: AgenticScope
      Returns all agent invocations recorded in this scope, in execution order.
      Specified by:
      agentInvocations in interface AgenticScope
      Returns:
      an unmodifiable list of all agent invocations
    • agentInvocations

      public List<AgentInvocation> agentInvocations(String agentName)
      Description copied from interface: AgenticScope
      Returns all agent invocations for the agent with the given name.
      Specified by:
      agentInvocations in interface AgenticScope
      Parameters:
      agentName - the name of the agent
      Returns:
      a list of invocations matching the agent name
    • agentInvocations

      public List<AgentInvocation> agentInvocations(Class<?> agentType)
      Description copied from interface: AgenticScope
      Returns all agent invocations for agents of the given type.
      Specified by:
      agentInvocations in interface AgenticScope
      Parameters:
      agentType - the class of the agent
      Returns:
      a list of invocations matching the agent type
    • toString

      public String toString()
      Overrides:
      toString in class Object
    • withErrorHandler

      public DefaultAgenticScope withErrorHandler(Function<ErrorContext, ErrorRecoveryResult> errorHandler)
    • handleError

      public ErrorRecoveryResult handleError(String agentName, AgentInvocationException exception)
    • registerCompensableExecution

      public void registerCompensableExecution(ToolExecution toolExecution, Consumer<ToolExecution> compensatingAction)
    • compensateAll

      public void compensateAll()
    • checkpoint

      public void checkpoint(AgenticScopeRegistry registry)
      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

      public boolean completePendingResponse(String responseId, Object value)
      Description copied from interface: AgenticScope
      Completes a DeferredResponse stored 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:
      completePendingResponse in interface AgenticScope
      Parameters:
      responseId - the unique identifier of the pending response
      value - the value to complete the response with, or null to complete it with no value, which removes the key from the state as AgenticScope.writeState(String, Object) does
      Returns:
      true if a matching pending response was found and completed
    • pendingResponseIds

      public Set<String> pendingResponseIds()
      Description copied from interface: AgenticScope
      Returns the identifiers of all DeferredResponse instances stored in this scope's state that have not yet been completed.
      Specified by:
      pendingResponseIds in interface AgenticScope
      Returns:
      a set of pending response identifiers
    • writeExecutionContext

      public void writeExecutionContext(String key, Object context)
      Description copied from interface: AgenticScope
      Stores non-serializable execution context in this scope, keyed by name.

      This allows custom Planner implementations to store runtime objects that are needed during execution but should not be persisted. The execution context is stored in a transient map 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:
      writeExecutionContext in interface AgenticScope
      Parameters:
      key - the key to use for this context (must not be null)
      context - the execution context instance to store (must not be null)
    • executionContext

      public Object executionContext(String key)
      Description copied from interface: AgenticScope
      Retrieves non-serializable execution context from this scope by key.

      Returns execution context previously stored via AgenticScope.writeExecutionContext(String, Object).

      Specified by:
      executionContext in interface AgenticScope
      Parameters:
      key - the key used to store the execution context
      Returns:
      the execution context instance previously stored for this key, or null if none exists
    • executionContextAs

      public <T> T executionContextAs(String key, Class<T> type)
      Description copied from interface: AgenticScope
      Retrieves 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:
      executionContextAs in interface AgenticScope
      Type Parameters:
      T - the type of the execution context
      Parameters:
      key - the key used to store the execution context
      type - the expected type of the execution context (for type-safe casting)
      Returns:
      the execution context instance previously stored for this key, or null if none exists