Session Management
Overview
The tRPC-Agent-Go framework provides powerful session management capabilities for maintaining conversation history and context during Agent-user interactions. With automatic persistence of conversation records, intelligent summary compression, and flexible storage backends, session management provides a complete infrastructure for building stateful intelligent Agents.
Purpose
Session manages the context of the current conversation, isolated by <appName, userID, SessionID>. It stores user messages, Agent replies, tool call results, and summaries generated from these contents, supporting multi-turn conversation scenarios.
Within the same conversation, it enables natural continuity between turns, preventing users from having to re-describe the same problem or provide the same parameters in each turn.
Key Features
- Context Management: Automatically loads conversation history for true multi-turn conversations
- Session Summary: Uses LLM to automatically compress long conversation history, significantly reducing token consumption while preserving key context
- Event Limit: Controls the maximum number of events stored per session to prevent memory overflow
- TTL Management: Supports automatic expiration and cleanup of session data
- Multiple Storage Backends: Supports Memory, SQLite, Redis, PostgreSQL, MySQL, and ClickHouse
- Concurrency Safe: Built-in read-write locks ensure safe concurrent access
- Automatic Management: Automatically handles session creation, loading, and updates when integrated with Runner
- Soft Delete Support: PostgreSQL/MySQL/ClickHouse support soft delete for data recovery
Quick Start
Integration with Runner
Session management in tRPC-Agent-Go is integrated into the Runner via runner.WithSessionService. The Runner automatically handles session creation, loading, updating, and persistence.
Supported Storage Backends: Memory, Redis, PostgreSQL, MySQL, ClickHouse
Default Behavior: If runner.WithSessionService is not configured, the Runner defaults to in-memory storage, and data will be lost after process restart.
Basic Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
Capabilities Provided by Runner
After integrating Session Service, the Runner automatically provides the following capabilities without manually calling any Session API:
- Automatic Session Creation: Automatically creates a session on first conversation (generates UUID if SessionID is empty)
- Automatic Session Loading: Automatically loads historical context at the start of each conversation
- Automatic Session Update: Automatically saves new events after conversation ends
- Context Continuity: Automatically injects conversation history into LLM input for multi-turn conversations
- Automatic Summary Generation (optional): Generates summaries asynchronously in the background when trigger conditions are met
Core Concepts
Session Structure
Session is the core data structure for session management:
| Field | Type | Description |
|---|---|---|
ID |
string |
Session ID |
AppName |
string |
Application name |
UserID |
string |
User ID |
State |
StateMap |
Session state (key-value pairs) |
Events |
[]event.Event |
Session event list |
Tracks |
map[Track]*TrackEvents |
Track event mapping |
Summaries |
map[string]*Summary |
Session summary mapping |
UpdatedAt |
time.Time |
Last update time |
CreatedAt |
time.Time |
Creation time |
Key Structure
A Session is uniquely identified by the Key structure:
Service Interface
All storage backends implement the session.Service interface:
Core Capabilities
1. Context Management
The core function of session management is maintaining conversation context, ensuring the Agent can remember historical interactions and respond intelligently based on history.
How it works:
- Automatically saves user input and AI responses for each turn
- Automatically loads historical events at the start of a new conversation
- Runner automatically injects historical context into LLM input
Default behavior: After Runner integration, context management is fully automated with no manual intervention required.
2. Event Limit
Controls the maximum number of events stored per session to prevent memory overflow from long conversations.
Mechanism:
- Automatically evicts oldest events when limit is exceeded (FIFO)
- Only affects storage, not business logic
- Applies to all storage backends
Configuration example:
Recommended configuration:
| Scenario | Recommended Value | Description |
|---|---|---|
| Short conversations | 100-200 | Customer support, single tasks |
| Medium sessions | 500-1000 | Daily assistant, multi-turn collaboration |
| Long sessions | 1000-2000 | Personal assistant, ongoing projects (use with summary) |
| Debug/Test | 50-100 | Quick validation, reduce noise |
3. TTL Management (Auto-Expiration)
Supports setting Time To Live for session data with automatic cleanup of expired data.
Supported TTL types:
- SessionTTL: Expiration time for session state and events
- AppStateTTL: Expiration time for app-level state
- UserStateTTL: Expiration time for user-level state
Configuration example:
TTL refresh behavior:
TTL is only refreshed on write operations (e.g., CreateSession, AppendEvent, UpdateSessionState). Read operations (GetSession) do not refresh TTL.
Expiration behavior:
| Storage Type | Expiration Mechanism | Auto Cleanup |
|---|---|---|
| Memory | Periodic scan + check on access | Yes |
| Redis | Native Redis TTL | Yes |
| PostgreSQL | Periodic scan (soft/hard delete) | Yes |
| MySQL | Periodic scan (soft/hard delete) | Yes |
| ClickHouse | Application-level cleanup + Native TTL | Yes |
Storage Backend Comparison
tRPC-Agent-Go provides six session storage backends for different scenarios:
| Storage Type | Use Case | Persistence | Distributed | Complex Queries |
|---|---|---|---|---|
| Memory | Dev/Test, small scale | ❌ | ❌ | ❌ |
| SQLite | Local persistence, single-node | ✅ | ❌ | ✅ |
| Redis | Production, distributed | ✅ | ✅ | ❌ |
| PostgreSQL | Production, complex queries | ✅ | ✅ | ✅ |
| MySQL | Production, complex queries | ✅ | ✅ | ✅ |
| ClickHouse | Production, massive data | ✅ | ✅ | ✅ |
Hook Capabilities
Session Service supports a Hook mechanism for intercepting and modifying event writes and session reads.
AppendEventHook
Intercept/modify/abort before event write. Useful for content safety, audit tagging, or blocking storage.
GetSessionHook
Intercept/modify/filter after session read. Useful for removing events with specific tags or dynamically supplementing Session state.
Usage Example
Chain of Responsibility: Hooks form a chain via next(). You can return early to short-circuit subsequent logic, and errors propagate upward.
Cross-Backend Consistency: All storage backends (Memory, Redis, PostgreSQL, MySQL, ClickHouse) have unified Hook support. Simply inject Hook slices when constructing the service — the usage is identical across all backends.
Advanced Usage
Using Session Service API Directly
In most cases, you should use session management through the Runner, which handles all details automatically. However, in some special scenarios (such as session management dashboards, data migration, analytics, etc.), you may need to operate the Session Service directly.
List Sessions
Delete Session
Get Session Details
Append Events to Session Directly
In some scenarios, you may need to append events to a session directly without calling the model. This is useful for:
- Pre-loading conversation history from external sources
- Inserting system messages or context before the first user query
- Recording user actions or metadata as events
- Programmatically building conversation context
Important: An Event can represent either a user request or a model response. When you use Runner.Run(), the framework automatically creates events for user messages and assistant replies.
Example: Append User Message
Example: Append System Message
Example: Append Assistant Message
Required Event Fields
When creating events with event.NewResponseEvent(), the following fields are required:
-
Function parameters:
invocationID(string): Unique identifier, typicallyuuid.New().String()author(string): Event author ("user","system", or agent name)response(*model.Response): Response object containing Choices
-
Response fields:
Choices([]model.Choice): At least one Choice withIndexandMessageMessage: Must containContentorContentParts
-
Auto-generated fields (set by
event.NewResponseEvent()):ID: Auto-generated UUIDTimestamp: Auto-set to current timeVersion: Auto-set toCurrentVersion
-
Persistence requirements:
Response != nil!IsPartial(or containsStateDelta)IsValidContent()returnstrue
Working with Runner
When you subsequently use Runner.Run() on the same session:
- Runner automatically loads the session (including all appended events)
- Converts session events to messages
- Includes all messages (appended + current) in the conversation context
- Sends them together to the model
All appended events become part of the conversation history and are available to the model in subsequent interactions.
Example: See examples/session/appendevent (code)
Track Events
Track events are a trajectory storage mechanism in Session that is independent of the main conversation events. They are primarily used for event storage in AGUI scenarios, allowing specific types of events to be recorded in a session without affecting the main conversation flow.
Interface:
The Track event API is defined on the session.TrackService interface, which is separate from session.Service:
Not all storage backends implement TrackService. A type assertion is required:
| Storage Backend | Implements TrackService |
|---|---|
| Memory (inmemory) | ✅ |
| Redis | ✅ |
| PostgreSQL | ✅ |
| MySQL | ✅ |
| ClickHouse | ❌ |
Basic usage:
Related Documentation
- Session Summary - Automatic compression of long conversation history
- Memory Storage - Development and testing environment
- SQLite Storage - Local persistence, single-node
- Redis Storage - Production distributed storage
- PostgreSQL Storage - Relational database storage
- MySQL Storage - Relational database storage
- ClickHouse Storage - Massive data storage