Every conversation between a user and your agent is tracked in a session. Sessions store the message history, custom state, and metadata needed to maintain context across multiple interactions.
How Sessions Work
When a message arrives, the interface looks up (or creates) a session keyed by three values:
This means:
- Each user gets a separate session per chat
- Group chats have one session per user within the group
- Sessions persist across messages until they expire
InterfaceSession
Each session contains:
Conversation History
The session’s messages list is passed to the agent on every call, giving it full context of the conversation:
History is automatically truncated to max_session_history (default: 50 messages) to stay within token limits. The most recent messages are always kept.
Session State
Use session_state to store custom per-user data that persists across messages:
State set in one message is available in all subsequent messages within the same session.
SessionManager
The SessionManager handles creation, lookup, and expiry of sessions. A default instance is created automatically, or you can provide your own.
Automatic Behavior
By default, sessions are:
- Created on the first message from a user/chat combination
- Reused on subsequent messages from the same user/chat
- Expired after
session_ttl_seconds of inactivity (default: 1 hour)
- Cleaned up automatically when expired sessions are encountered
Custom SessionManager
SessionManager API
Manual Session Access
Session TTL
Sessions expire based on last_activity_at. Every incoming message updates this timestamp via session.touch(). Once the time since last activity exceeds session_ttl_seconds, the session is considered expired and will be removed on the next access or cleanup.
When a session expires, the next message from that user starts a fresh conversation with no history.
History Truncation
Long conversations are automatically truncated to prevent token limit issues:
The session’s truncate_history(max_messages) method removes the oldest messages, always keeping the most recent ones.
SessionManager is thread-safe. All operations use internal locking, so it is safe to use with concurrent message processing.