State Scoping
State is automatically scoped using prefixes:Session State
No prefix - Scoped to current sessionTemporary data for this conversation
User State
user: prefix - Shared across user’s sessionsPersistent user preferencesApp State
app: prefix - Shared across all usersGlobal configuration and statisticsTemp State
temp: prefix - Never persistedScratch data for current invocationState Class
TheState class provides a dict-like interface with delta tracking:
Creating State
Using State in Agents
State is automatically managed by the session:- Session State
- User State
- App State
- Temp State
Default scope for conversation-specific data:Example:
State Delta Tracking
Only changed state is persisted, improving performance:How Delta Tracking Works
In Session Events
State in Tools
Tools can read and modify state viaToolContext:
State Persistence
How different session services handle state:- InMemorySessionService
- DatabaseSessionService
Maintains state in memory with three separate maps:
State Best Practices
Choosing State Scope
Choosing State Scope
Use Session State when:
- Data is specific to this conversation
- Should reset for new conversations
- Temporary working data
- Data should persist across sessions
- User preferences and settings
- Accumulated user-specific data
- Data shared by all users
- Global configuration
- System-wide statistics
- Data only needed for this invocation
- Intermediate calculations
- Not worth persisting
State Structure
State Structure
- Keep state flat when possible
- Use descriptive key names
- Document your state schema
- Validate state before use
- Set default values for missing keys
Performance
Performance
- Only include changed fields in stateDelta
- Avoid storing large objects in state
- Use artifacts for file data
- Clean up unused state keys
- Consider state size for context limits
State Types
State Types
- Use TypeScript interfaces for state
- Validate state shape
- Provide type guards
- Document expected types