session.go
Overview
The session.go file defines core interfaces and data structures for managing user-agent interaction sessions within the system. A session represents a continuous conversation or interaction thread between a user and one or more agents, encapsulating the conversation history, session state, and metadata. This file provides abstractions for session identity, persistent session state as a key-value store, and the sequence of interaction events that make up the conversation.
It serves as the foundation for tracking conversation progress, storing user or app-specific state, and managing event histories such as user inputs, agent responses, and function call activities. The interfaces and types defined here are designed to be implemented by different storage backends, enabling flexible and pluggable session persistence solutions.
This file is a key component of the Session Management topic, where session lifecycle, state management, and event history are handled, supporting workflows involving agents, LLM responses, and function executions.
Key Interfaces and Types
Session Interface
Represents a single user-agent interaction thread. It provides accessors for session metadata, state, and event history.
Methods:
ID() string: Returns the globally unique identifier of the session.AppName() string: Returns the name of the application the session belongs to.UserID() string: Returns the user identifier associated with the session.State() State: Provides access to the session's mutable key-value state.Events() Events: Provides access to the chronological list of events in the session.LastUpdateTime() time.Time: Returns the timestamp of the last update to the session.
Usage Example:
var sess Session
sessionID := sess.ID()
userID := sess.UserID()
state := sess.State()
events := sess.Events()
State Interface
Defines a mutable key-value store used to store session state data scoped to the session.
Methods:
Get(key string) (any, error): Retrieves the value associated withkey. ReturnsErrStateKeyNotExistif missing.Set(key string, value any) error: Sets or updates the value forkey.All() iter.Seq2[string, any]: Returns an iterator over all key-value pairs in the state.
The state keys typically use prefixes such as app:, user:, or temp: (defined as constants) to specify scope.
ReadonlyState Interface
A read-only variant of the State interface, exposing only Get and All methods. Useful for contexts where mutation is disallowed.
Events Interface
Represents an ordered list of Event objects that track the sequence of interactions in a session.
Methods:
All() iter.Seq[*Event]: Iterator over all events preserving order.Len() int: Number of events in the sequence.At(i int) *Event: Access event by index.
Event Struct
Encapsulates an individual interaction or message in the session conversation. It embeds model.LLMResponse to include LLM-generated content.
Fields:
ID string: Unique event identifier.Timestamp time.Time: When the event occurred.InvocationID string: Identifier linking to the agent invocation context.Branch string: Dot-separated string representing hierarchical sub-agent branching.Author string: Name of the event's author (user or agent).Actions EventActions: Actions performed or triggered by this event.LongRunningToolIDs []string: IDs of any long-running function calls associated with the event.
Methods:
IsFinalResponse() bool: Determines whether this event is considered the final response from an agent for the invocation. It considers flags such as skipped summarization, ongoing function calls, partial responses, and trailing code execution results.
Creation:
NewEvent(invocationID string) *Event: Factory function to create a new event with a fresh UUID and current timestamp.
EventActions Struct
Describes side effects or control actions attached to an event.
Fields:
StateDelta map[string]any: Changes to session state caused by this event.ArtifactDelta map[string]int64: Updates to artifact versions; key is filename, value is version number.SkipSummarization bool: If true, disables automatic summarization of function responses.TransferToAgent string: Agent ID to which the session should transfer.Escalate bool: Indicates escalation to a higher-level agent.
Constants
Defines key prefixes for scoping session state keys:
KeyPrefixApp = "app:": Application-wide shared state.KeyPrefixTemp = "temp:": Temporary state for the current invocation only.KeyPrefixUser = "user:": User-scoped state shared across sessions in the same app.
Errors
ErrStateKeyNotExist: Returned when a requested key does not exist in the state.
Helper Functions (Internal)
These functions inspect an LLMResponse embedded in an event to detect special content types:
hasFunctionCalls(resp *model.LLMResponse) bool: Returns true if the response contains any function call instructions.hasFunctionResponses(resp *model.LLMResponse) bool: Returns true if the response contains function call responses.hasTrailingCodeExecutionResult(resp *model.LLMResponse) bool: Returns true if the last content part is a code execution result.
These checks are used mainly in Event.IsFinalResponse() to determine whether the event marks a final agent output or if further processing is expected.
Interactions with Other System Components
The
Sessioninterface and related types integrate closely with the Agent Invocation Context, where the session instance is passed to agents and workflows during execution.The
Eventstruct leverages themodel.LLMResponsetype from the LLM integration layer (LLM Integration and Agents) to represent model output and function call data.The state key prefixes (
app:,user:,temp:) correspond to concepts from Session State Injection and Agent Workflow Management, enabling dynamic data injection and scoping.Implementations of the
SessionandStateinterfaces may be backed by storage layers such as In-Memory Session Service or Database Session Service according to system configuration.EventActionsenable control flow features like agent escalation and transfer, which relate to agent lifecycle management (Agent Lifecycle and Callbacks) and agent selection (Agent Selection Logic).
Mermaid Class Diagram
classDiagram
class Session {
+ID() string
+AppName() string
+UserID() string
+State() State
+Events() Events
+LastUpdateTime() time.Time
}
class State {
+Get(string) (any, error)
+Set(string, any) error
+All() iter.Seq2
}
class ReadonlyState {
+Get(string) (any, error)
+All() iter.Seq2
}
class Events {
+All() iter.Seq
+Len() int
+At(int) *Event
}
class Event {
+ID string
+Timestamp time.Time
+InvocationID string
+Branch string
+Author string
+Actions EventActions
+LongRunningToolIDs []string
+IsFinalResponse() bool
}
class EventActions {
+StateDelta map[string]any
+ArtifactDelta map[string]int64
+SkipSummarization bool
+TransferToAgent string
+Escalate bool
}
Session --> State
Session --> Events
Events --> Event
Event --> EventActions
State <|-- ReadonlyState
Detailed Explanation of Important Implementation Details
Session State and Scoping
The session state is designed as a generic key-value store accessible via the State interface. Keys are prefixed to indicate their scope:
app:keys are shared across all users and sessions within the application.user:keys are shared among all sessions of a specific user.temp:keys are ephemeral and valid only during the current agent invocation.
This scoping mechanism allows fine-grained control over state visibility and lifecycle, critical for supporting features like multi-user applications, session persistence, and temporary invocation data.
Event Model and Finality Detection
Each Event embeds an LLM response and metadata about the conversation turn or action. The IsFinalResponse method uses a combination of heuristics to determine if the event represents a completed agent response:
If summarization is skipped or there are ongoing long-running function calls, the event is considered final.
If the LLM response contains no function calls or responses, is not partial, and does not have trailing code execution results, it is final.
This logic ensures that downstream components can recognize when an agent's turn is complete and ready for user consumption or further processing.
Use of UUIDs and Timestamps
Events are assigned unique UUIDs at creation (NewEvent), ensuring traceability and uniqueness in distributed environments. Timestamps are recorded using time.Now() to mark event occurrence, important for ordering and auditing.
Summary of File Role in the System
The session.go file establishes the foundational abstractions for session identity, state management, and event tracking in user-agent conversations. It plays a critical role in the lifecycle of agent interactions by enabling persistent, scoped state management and detailed event histories. The abstractions here allow the rest of the system to build sophisticated agent workflows, stateful memory, and event-driven logic over a consistent and extensible session model.
This file's constructs are utilized by other components such as agents (LLM Integration and Agents), session service implementations (In-Memory Session Service, Database Session Service), and agent runners (Agent Execution Runner) to support complex conversational AI scenarios.