session.go
Overview
The session.go file defines core data structures and helper functions for managing an agent's session within the system. A session encapsulates the interaction state of an agent with a user, including session metadata, persistent state, and event history. This file primarily focuses on the representation, validation, and transformation of session data between internal models and external session entities.
This file supports the session lifecycle by enabling:
Construction and validation of session objects (
Sessionstruct).Conversion from external session representations (
session.Session) to internal models.Parsing and validation of session identifiers from HTTP parameters.
Management of session state and event collections.
It plays a key role in the Session Management topic by providing the foundational data structures and conversion logic used throughout the session handling and persistence layers.
Data Structures
Session
type Session struct {
ID string `json:"id"`
AppName string `json:"appName"`
UserID string `json:"userId"`
UpdatedAt int64 `json:"lastUpdateTime"`
Events []Event `json:"events"`
State map[string]any `json:"state"`
}
Represents the state of an agent's session with the following fields:
ID— Unique identifier of the session.AppName— Name of the application associated with the session.UserID— Identifier for the user owning the session.UpdatedAt— Timestamp (Unix epoch) marking the last update to the session.Events— Slice ofEventobjects representing the event history.State— Arbitrary key-value map holding the session's persistent state.
This struct is the core model for session data passed between internal components and external APIs.
CreateSessionRequest
type CreateSessionRequest struct {
State map[string]any `json:"state"`
Events []Event `json:"events"`
}
Defines the payload structure for creating a new session. It includes:
State— Initial session state map.Events— Initial event list.
This type facilitates session creation requests likely used by REST handlers or service layers.
SessionID
type SessionID struct {
ID string `mapstructure:"session_id,optional"`
AppName string `mapstructure:"app_name,required"`
UserID string `mapstructure:"user_id,required"`
}
Encapsulates the identifying parameters of a session. Fields:
ID— Optional session identifier.AppName— Required application name.UserID— Required user identifier.
Used primarily for decoding and validating session identification data from HTTP route variables or other map-based data sources.
Functions and Methods
SessionIDFromHTTPParameters
func SessionIDFromHTTPParameters(vars map[string]string) (SessionID, error)
Parses and validates session identification parameters from a map of HTTP variables.
Parameters:
vars: Map of string keys and values representing HTTP route parameters.
Returns:
SessionID: Parsed session identifier struct.error: Non-nil if required parameters are missing or decoding fails.
Usage Example:
vars := map[string]string{
"app_name": "chatbot",
"user_id": "user123",
}
sessionID, err := SessionIDFromHTTPParameters(vars)
if err != nil {
// handle error
}
Details:
Uses
mapstructuredecoder configured for weakly typed input to flexibly parse strings.Validates presence of required parameters
app_nameanduser_id.Returns explicit errors if validation fails.
FromSession
func FromSession(session session.Session) (Session, error)
Converts an external session.Session interface object to an internal Session model.
Parameters:
session: The external session object to convert.
Returns:
Session: The internal session representation.error: Validation error if the resulting session is invalid.
Implementation Details:
Creates a shallow copy of the session state using
maps.Insertto clone all key-value pairs.Iterates over all events in the external session, converting each using
FromSessionEvent.Populates fields
ID,AppName,UserID, andUpdatedAtfrom the external session.Validates the constructed session before returning.
This function bridges the external session abstraction with this package's internal representation critical for storage, manipulation, or API response.
(Session) Validate
func (s Session) Validate() error
Validates the integrity and completeness of a Session instance.
Returns:
error: Returns a descriptive error if validation fails, otherwisenil.
Validation rules:
AppName,UserID, andIDmust be non-empty.UpdatedAtmust be non-zero.Statemap must not benil.Eventsslice must not benil.
This method ensures that session data conforms to expected invariants before further processing or storage.
Important Implementation Details
The use of
mapstructurefor decoding HTTP parameters allows flexible parsing and loose coupling with HTTP routing frameworks.The
FromSessionfunction usesmaps.Insertto clone the state map, ensuring isolation from the external session’s internal state.Events are converted via a separate function
FromSessionEvent(not defined in this file), indicating event transformation logic is modularized.Validation is performed both during conversion and as a standalone method, enforcing consistent session data integrity.
Timestamp is stored as an int64 Unix epoch for simplicity and uniformity across components.
Interactions with Other Components
The file imports the
sessionpackage from"google.golang.org/adk/session", indicating integration with an external or core session abstraction.The
Eventtype is referenced but defined elsewhere, linking this model to the event management subsystem.Session ID parsing supports HTTP parameter maps, connecting this file with REST API layers, likely the REST API and Web Launchers topic.
Validation and conversion logic here will be utilized by session storage services such as In-Memory Session Service and Database Session Service.
This model is foundational for the Session Management topic, enabling persistent user-agent interaction sessions with state and event tracking.
Diagram: Session Structure and Function Relationships
classDiagram
class Session {
+string ID
+string AppName
+string UserID
+int64 UpdatedAt
+[]Event Events
+map[string]any State
+Validate() error
}
class CreateSessionRequest {
+map[string]any State
+[]Event Events
}
class SessionID {
+string ID
+string AppName
+string UserID
}
SessionID ..> SessionIDFromHTTPParameters
SessionIDFromHTTPParameters : returns SessionID, error
Session ..> FromSession
FromSession : returns Session, error
This diagram illustrates the primary data structures (Session, CreateSessionRequest, SessionID) and their associated key functions (SessionIDFromHTTPParameters, FromSession, and Validate). It highlights relationships such as conversion and validation centered around the Session struct.
This file forms a critical model and utility layer for managing agent sessions, validating their state, and adapting external session objects into the internal domain used across the agent framework. It directly supports the session lifecycle by defining core session data and ensuring its correctness.