Package com.google.genkit.ai.session
Class SessionContext
java.lang.Object
com.google.genkit.ai.session.SessionContext
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");
});
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classException thrown when session operations fail. -
Method Summary
Modifier and TypeMethodDescriptionstatic voidClears the current session.static <S> Session<S> Gets the current session.static <S> Session<S> Gets the current session if available.static booleanChecks if currently running within a session context.static <S> voidrunWithSession(Session<S> session, Runnable runnable) Runs a runnable within a session context.static <S,T> T runWithSession(Session<S> session, Callable<T> callable) Runs a function within a session context.static voidsetSession(Session<?> session) Sets the current session.
-
Method Details
-
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
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
Runs a function within a session context.- Type Parameters:
S- the session state typeT- the return type- Parameters:
session- the session to usecallable- the function to run- Returns:
- the result of the function
- Throws:
Exception- if the function throws an exception
-
runWithSession
Runs a runnable within a session context.- Type Parameters:
S- the session state type- Parameters:
session- the session to userunnable- the runnable to execute
-
setSession
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.
-