Documentation Index
Fetch the complete documentation index at: https://docs.upsonic.ai/llms.txt
Use this file to discover all available pages before exploring further.
What is Memory?
Memory in Upsonic is a sophisticated system that allows your AI agents to remember and learn from previous interactions. Just like humans, agents need memory to provide personalized, contextual responses and maintain continuity across conversations. The Memory system provides three main types of memory capabilities:
- Full Session Memory: Stores complete conversation history for context-aware responses
- Summary Memory: Maintains evolving summaries of conversations for long-term understanding
- User Analysis Memory: Builds persistent user profiles based on interaction patterns
Core Principles For Memory
When implementing Memory in your agents, ensure you understand these key concepts:
- Storage Providers: Choose the right storage backend (in-memory, JSON, PostgreSQL, MongoDB, Redis, SQLite) for your use case
- Memory Types: Enable only the memory types you need to balance performance and functionality
- Session Management: Properly manage session IDs and user IDs for memory persistence
- Context Injection: Memory automatically injects relevant context into your agent’s prompts
Memory Configuration Options
The Memory system offers flexible configuration to suit different requirements:
Memory Types:
full_session_memory: Stores complete chat history
summary_memory: Maintains conversation summaries
user_analysis_memory: Builds user profiles
Storage Options:
InMemoryStorage: Fast, ephemeral storage for development
JSONStorage: File-based storage for simple applications
PostgresStorage: Production-grade relational database storage
MongoStorage: Scalable NoSQL storage
RedisStorage: High-performance in-memory storage
SqliteStorage: Lightweight local database storage
Let’s Create an Agent with Memory Capabilities
In this example, we’ll create an agent that remembers user preferences and maintains conversation context across multiple interactions.
uv pip install upsonic sqlalchemy aiosqlite
# pip install upsonic sqlalchemy aiosqlite
# Upsonic Docs: Using Memory in your Agent
# https://docs.upsonic.ai/guides/using_memory_in_your_agent
# Imports
from upsonic import Agent
from upsonic import Task
from upsonic.storage import InMemoryStorage, Memory
# Create a storage provider
storage = InMemoryStorage()
# Create a Memory instance with all memory types enabled
memory = Memory(
storage=storage,
session_id="user_session_123",
user_id="user_456",
full_session_memory=True, # Remember complete conversations
summary_memory=True, # Maintain conversation summaries
user_analysis_memory=True, # Build user profiles
dynamic_user_profile=True, # Automatically adapt profile schema
num_last_messages=10, # Limit context to last 10 messages
debug=True # Enable debug logging
)
# Create an Agent with Memory
personal_assistant = Agent(
model="anthropic/claude-sonnet-4-5",
name="Personal Assistant",
role="Personal AI Assistant with Memory",
goal="Provide personalized assistance by remembering user preferences and conversation history",
instructions="""
Always reference previous conversations when relevant.
Adapt your responses based on the user's profile and preferences.
Use the conversation summary to provide context-aware assistance.
""",
memory=memory
)
# Example tasks that demonstrate memory capabilities
task1 = Task(
description="I prefer to be called 'Alex' and I'm interested in machine learning",
)
task2 = Task(
description="What did we discuss in our previous conversation?",
)
task3 = Task(
description="Based on what you know about me, suggest a learning path for AI",
)
# Execute tasks to build memory
print("=== Task 1: Building User Profile ===")
result1 = personal_assistant.print_do(task1)
print(f"Response: {result1}")
print("\n=== Task 2: Testing Memory Recall ===")
result2 = personal_assistant.print_do(task2)
print(f"Response: {result2}")
print("\n=== Task 3: Using Memory for Personalization ===")
result3 = personal_assistant.print_do(task3)
print(f"Response: {result3}")
# Check memory statistics
print(f"\n=== Memory Statistics ===")
print(f"Session ID: {memory.session_id}")
print(f"User ID: {memory.user_id}")
print(f"Full Session Memory: {memory.full_session_memory_enabled}")
print(f"Summary Memory: {memory.summary_memory_enabled}")
print(f"User Analysis Memory: {memory.user_analysis_memory_enabled}")
Advanced Memory Configuration
Using Different Storage Providers
from upsonic.storage import PostgresStorage
postgres_storage = PostgresStorage(
db_url="postgresql://user:pass@localhost:5432/upsonic_db",
db_schema="public",
session_table="agent_sessions",
user_memory_table="user_profiles"
)
from upsonic.storage import RedisStorage
# Redis Storage for High Performance
redis_storage = RedisStorage(
db_url="redis://localhost:6379/0",
db_prefix="upsonic",
expire=86400 # 24 hours TTL
)
from upsonic.storage import JSONStorage
# JSON Storage for Simple Applications
json_storage = JSONStorage(
db_path="./data/memory"
)
Custom User Profile Schemas
You can define custom user profile schemas to structure how your agent learns about users:
from pydantic import BaseModel, Field
from upsonic import Agent, Task
from upsonic.storage import Memory
from upsonic.storage.json import JSONStorage
class CustomUserProfile(BaseModel):
expertise_level: str = Field(description="User's expertise level in the domain")
preferred_language: str = Field(description="User's preferred programming language")
learning_goals: list[str] = Field(description="User's learning objectives")
communication_style: str = Field(description="User's preferred communication style")
# Initialize JSON storage for custom profile
json_storage = JSONStorage("./memory_data")
# Create Memory with custom profile schema
custom_memory = Memory(
storage=json_storage,
session_id="session_789",
user_id="user_101",
user_analysis_memory=True,
user_profile_schema=CustomUserProfile,
dynamic_user_profile=False, # Use our custom schema instead of dynamic
model="anthropic/claude-sonnet-4-5"
)
# Create agent with custom memory
profile_agent = Agent(
model="anthropic/claude-sonnet-4-5",
name="Profile Builder",
role="User Profile Specialist",
memory=custom_memory
)
# Build user profile with structured data
profile_task = Task(
description="I'm an intermediate Python developer. I prefer Python and want to learn advanced async programming and system design. Please communicate in a technical but friendly way."
)
result = profile_agent.print_do(profile_task)
# The agent now has a structured understanding of the user based on CustomUserProfile schema
Benefits of Custom Schemas:
- Structured data collection for specific use cases
- Type-safe user profile management
- Better control over what information is tracked
- Easier integration with analytics and reporting systems
Memory with Model Provider
memory_with_model = Memory(
storage=storage,
session_id="session_456",
user_id="user_789",
summary_memory=True,
user_analysis_memory=True,
model="anthropic/claude-sonnet-4-5", # For generating summaries and analyzing traits
debug=True
)
Memory Best Practices
1. Choose the Right Storage Provider
- Development/Testing: Use
InMemoryStorage for fast iteration
- Simple Applications: Use
JSONStorage for file-based persistence
- Production Web Apps: Use
PostgresStorage or MongoStorage for scalability
- High-Performance: Use
RedisStorage for caching and speed
- Full Session Memory: Enable for chatbots and support agents
- Summary Memory: Use for long conversations to maintain context
- User Analysis Memory: Essential for personalized experiences
3. Manage Session Lifecycles
# Create unique session IDs for different conversation contexts
import uuid
session_id = f"chat_session_{uuid.uuid4()}"
user_id = f"user_{uuid.uuid4()}"
memory = Memory(
storage=storage,
session_id=session_id,
user_id=user_id,
full_session_memory=True
)
4. Monitor Memory Usage
# Check memory statistics
print(f"Memory Configuration:")
print(f"- Full Session Memory: {memory.full_session_memory_enabled}")
print(f"- Summary Memory: {memory.summary_memory_enabled}")
print(f"- User Analysis Memory: {memory.user_analysis_memory_enabled}")
print(f"- Max Messages: {memory.num_last_messages}")
print(f"- Feed Tool Results: {memory.feed_tool_call_results}")
Memory in Multi-Agent Teams
Memory can be shared across multiple agents in a team, allowing all agents to access the same conversation history and context:
from upsonic import Team, Agent, Task
from upsonic.storage import Memory, InMemoryStorage
# Initialize storage
storage = InMemoryStorage()
# Create a shared memory instance
shared_memory = Memory(
storage=storage,
session_id="team_session_123",
user_id="user_456",
full_session_memory=True,
summary_memory=True,
model="anthropic/claude-sonnet-4-5" # Required for summary generation
)
# Define tasks for the team
research_task = Task(
description="Research the latest trends in AI and machine learning for 2024"
)
writing_task = Task(
description="Write a comprehensive article based on the research findings"
)
# Create agents with shared memory
research_agent = Agent(
model="anthropic/claude-sonnet-4-5",
name="Research Agent",
role="Research Specialist",
goal="Conduct thorough research on AI trends",
memory=shared_memory
)
writing_agent = Agent(
model="anthropic/claude-sonnet-4-5",
name="Writing Agent",
role="Content Writer",
goal="Create engaging content from research",
memory=shared_memory
)
# Create a team with shared memory
research_team = Team(
agents=[research_agent, writing_agent],
memory=shared_memory,
tasks=[research_task, writing_task]
)
# Execute team tasks
print("=== Executing Team Tasks with Shared Memory ===")
result = research_team.print_do()
# Both agents can now access the shared conversation history
print(f"\n=== Memory Statistics ===")
print(f"Session ID: {shared_memory.session_id}")
print(f"User ID: {shared_memory.user_id}")
print(f"Full Session Memory: {shared_memory.full_session_memory_enabled}")
print(f"Summary Memory: {shared_memory.summary_memory_enabled}")
Key Benefits of Shared Memory in Teams:
- All agents have access to the complete conversation history
- Context is preserved across different agent interactions
- Team coordination is improved through shared understanding
- User preferences and patterns are available to all team members
Troubleshooting Memory Issues
Common Problems and Solutions
-
Memory Not Persisting:
- Ensure storage provider is properly connected
- Check that session_id and user_id are set
- Verify memory types are enabled
-
Context Not Being Injected:
- Check that
context_formatted is being set
- Verify memory manager is properly integrated
- Ensure storage operations are successful
-
Performance Issues:
- Limit
num_last_messages for large conversations
- Use appropriate storage provider for your scale
- Consider disabling unused memory types
Debug Mode
Enable debug mode to troubleshoot memory issues:
memory = Memory(
storage=storage,
session_id="debug_session",
user_id="debug_user",
full_session_memory=True,
debug=True # Enable detailed logging
)
Need more advanced features?
The Memory system offers several advanced configurations to enhance your agent’s capabilities:
-
Custom Storage Providers: Integrate with various storage backends such as PostgreSQL, MongoDB, Redis, or SQLite to suit your scalability and performance needs.
-
Selective Memory Types: Enable or disable specific memory types (full session, summary, user analysis) to optimize resource usage and functionality.
-
Dynamic User Profiles: Utilize dynamic user profiles that adapt schema based on interaction patterns, allowing for personalized user experiences.
-
Context Management: Configure the number of last messages to retain in context, balancing between context richness and performance.
-
Memory Modes: Choose between ‘update’ and ‘replace’ modes for user profile management to control how new information is integrated with existing data.
-
Tool Call Integration: Configure whether tool call results are included in memory storage for comprehensive conversation tracking.
-
Debugging Tools: Activate debug mode to monitor memory operations, aiding in development and troubleshooting.
For detailed examples and advanced patterns, see our comprehensive Memory Concept Documentation.