Class ThreadSessionManager

java.lang.Object
io.agentscope.spring.boot.agui.common.ThreadSessionManager

public class ThreadSessionManager extends Object
Manages agent sessions by threadId for server-side memory management.

This manager maintains a pool of agent instances, each associated with a threadId. When server-side memory is enabled, the same agent instance is reused for requests with the same threadId, preserving conversation history across requests.

Usage:


 ThreadSessionManager manager = new ThreadSessionManager(1000, 30);

 // Get or create an agent for a thread
 Agent agent = manager.getOrCreateAgent("thread-123", "default", () -> createAgent());

 // Check if agent has memory
 boolean hasMemory = manager.hasMemory("thread-123");

 // Clean up expired sessions
 manager.cleanupExpiredSessions();
 
  • Constructor Details

    • ThreadSessionManager

      public ThreadSessionManager(int maxSessions, int sessionTimeoutMinutes)
      Creates a new ThreadSessionManager.
      Parameters:
      maxSessions - Maximum number of sessions to maintain
      sessionTimeoutMinutes - AgentStateStore timeout in minutes (0 = no timeout)
  • Method Details

    • getOrCreateAgent

      public io.agentscope.core.agent.Agent getOrCreateAgent(String threadId, String agentId, Supplier<io.agentscope.core.agent.Agent> agentFactory)
      Get or create an agent for the given threadId.

      This method is thread-safe. It uses atomic operations to ensure that concurrent requests for the same threadId will share the same agent instance.

      Parameters:
      threadId - The thread identifier
      agentId - The agent type identifier
      agentFactory - Factory to create new agents if needed
      Returns:
      The agent for this thread
    • hasMemory

      public boolean hasMemory(String threadId)
      Check if a session exists and has memory for the given threadId.
      Parameters:
      threadId - The thread identifier
      Returns:
      true if the session exists and the agent has non-empty memory
    • getSession

      public Optional<ThreadSessionManager.ThreadSession> getSession(String threadId)
      Get the session for a threadId if it exists.
      Parameters:
      threadId - The thread identifier
      Returns:
      Optional containing the session, or empty if not found
    • removeSession

      public boolean removeSession(String threadId)
      Remove a session by threadId.
      Parameters:
      threadId - The thread identifier
      Returns:
      true if a session was removed
    • cleanupExpiredSessions

      public void cleanupExpiredSessions()
      Clean up sessions that have been inactive for longer than the timeout.
    • getSessionCount

      public int getSessionCount()
      Get the current number of active sessions.
      Returns:
      Number of sessions
    • clear

      public void clear()
      Clear all sessions.