Class SessionContext

java.lang.Object
com.google.genkit.ai.session.SessionContext

public final class SessionContext extends Object
Provides access to the current session context.

This class uses ThreadLocal to store the current session, making it accessible from within tool execution. This enables tools to access and modify session state during their execution.

Example usage in a tool:


 Tool<Input, Output> myTool = genkit.defineTool(
 		ToolConfig.<Input, Output>builder().name("myTool").description("A tool that accesses session state")
 				.inputSchema(Input.class).outputSchema(Output.class).build(),
 		(input, ctx) -> {
 			// Access current session from within tool
 			Session<MyState> session = SessionContext.currentSession();
 			MyState state = session.getState();

 			// Update session state
 			session.updateState(new MyState(state.getName(), state.getCount() + 1));

 			return new Output("Updated");
 		});
 
  • Method Details

    • currentSession

      public static <S> Session<S> currentSession()
      Gets the current session.
      Type Parameters:
      S - the session state type
      Returns:
      the current session
      Throws:
      SessionContext.SessionException - if not running within a session
    • getCurrentSession

      public static <S> Session<S> getCurrentSession()
      Gets the current session if available.
      Type Parameters:
      S - the session state type
      Returns:
      the current session, or null if not in a session context
    • hasSession

      public static boolean hasSession()
      Checks if currently running within a session context.
      Returns:
      true if in a session context
    • runWithSession

      public static <S, T> T runWithSession(Session<S> session, Callable<T> callable) throws Exception
      Runs a function within a session context.
      Type Parameters:
      S - the session state type
      T - the return type
      Parameters:
      session - the session to use
      callable - the function to run
      Returns:
      the result of the function
      Throws:
      Exception - if the function throws an exception
    • runWithSession

      public static <S> void runWithSession(Session<S> session, Runnable runnable)
      Runs a runnable within a session context.
      Type Parameters:
      S - the session state type
      Parameters:
      session - the session to use
      runnable - the runnable to execute
    • setSession

      public static void setSession(Session<?> session)
      Sets the current session. This is typically called internally by Chat.
      Parameters:
      session - the session to set
    • clearSession

      public static void clearSession()
      Clears the current session.