A memory management system for AI agents to store and retrieve user interactions
Project description
Agent Memory
A memory management system for AI agents to store and retrieve user interactions and preferences.
Features
- 🧠 Persistent Memory Storage: Store conversations, user preferences, facts, and context
- 🔍 Powerful Search: Find memories by content, tags, importance, date ranges, and more
- 🏷️ Flexible Tagging: Organize memories with custom tags
- ⏰ Expiration Support: Set automatic expiration for temporary memories
- 📊 Importance Scoring: Rank memories by importance (0.0 to 1.0)
- 📈 Access Tracking: Monitor memory usage with access counts and timestamps
- 🗃️ Multiple Backends: SQLite (default), PostgreSQL, and other SQLAlchemy-supported databases
- 🔧 Type Safety: Full type hints and Pydantic models
- 🧪 Well Tested: Comprehensive test suite
Installation
pip install agent-memory
For development:
pip install agent-memory[dev]
Quick Start
from agent_memory import AgentMemory, MemoryType
# Initialize the memory system
memory = AgentMemory()
# Add a conversation memory
conversation = memory.add_conversation_memory(
user_id="user123",
user_message="I love Python programming",
agent_response="That's great! Python is a versatile language.",
importance=0.8,
tags=["programming", "python"]
)
# Add a user preference
preference = memory.add_user_preference(
user_id="user123",
preference="programming_language",
value="Python"
)
# Search for memories
memories = memory.search_memories(
user_id="user123",
content_search="Python",
min_importance=0.5
)
# Get all user preferences
preferences = memory.get_user_preferences("user123")
print(preferences) # {"programming_language": "Python"}
Core Concepts
Memory Types
Agent Memory supports different types of memories:
CONVERSATION: Dialog between user and agentUSER_PREFERENCE: User settings and preferencesFACT: Factual information about the userCONTEXT: Contextual information for conversationsGOAL: User goals and objectivesFEEDBACK: User feedback on agent responses
Memory Properties
Each memory contains:
id: Unique identifier (UUID)user_id: User identifieragent_id: Optional agent identifiercontent: The actual memory contentmemory_type: Type of memory (see above)importance: Importance score (0.0 to 1.0)tags: List of tags for organizationmetadata: Additional structured datatimestamp: When memory was createdexpires_at: Optional expiration date
Advanced Usage
Custom Database
# Use PostgreSQL
memory = AgentMemory(
database_url="postgresql://user:pass@localhost/memories"
)
# Use custom SQLite location
memory = AgentMemory(
database_url="sqlite:///path/to/custom/memories.db"
)
Advanced Searching
from datetime import datetime, timedelta
# Complex search query
memories = memory.search_memories(
user_id="user123",
memory_type=MemoryType.CONVERSATION,
tags=["important", "work"],
min_importance=0.7,
created_after=datetime.now() - timedelta(days=7),
limit=20,
offset=0
)
Memory Management
# Update memory
updated = memory.update_memory(
memory_id=conversation.id,
importance=0.9,
tags=["programming", "python", "favorite"]
)
# Delete memory
memory.delete_memory(conversation.id)
# Cleanup expired memories
removed_count = memory.cleanup_expired()
Statistics and Analytics
# Get memory statistics
stats = memory.get_memory_stats(user_id="user123")
print(f"Total memories: {stats['total_memories']}")
print(f"By importance: {stats['by_importance']}")
print(f"By type: {stats['by_type']}")
API Reference
AgentMemory
Main class for memory management.
__init__(database_url=None, auto_cleanup=True)
Initialize the memory system.
database_url: Database connection string (defaults to local SQLite)auto_cleanup: Whether to automatically clean expired memories
add_memory(user_id, content, memory_type=CONVERSATION, **kwargs)
Add a new memory.
Parameters:
user_id(str): User identifiercontent(str): Memory contentmemory_type(MemoryType): Type of memoryagent_id(str, optional): Agent identifierimportance(float): Importance score (0.0-1.0)tags(List[str]): Tags for organizationmetadata(dict): Additional metadataexpires_in_days(int): Days until expiration
search_memories(**filters)
Search for memories with flexible filtering.
Filters:
user_id,agent_id,memory_typecontent_search: Search in contenttags: Filter by tagsmin_importance,max_importance: Importance rangecreated_after,created_before: Date rangelimit,offset: Paginationinclude_expired: Include expired memories
Convenience Methods
add_conversation_memory(): Add user-agent conversationadd_user_preference(): Add user preferenceget_user_preferences(): Get all preferences as dictget_user_memories(): Get all memories for usercleanup_expired(): Remove expired memoriesget_memory_stats(): Get memory statistics
Development
Setup
git clone https://github.com/yourusername/agent-memory.git
cd agent-memory
pip install -e .[dev]
Running Tests
pytest
Code Quality
# Format code
black agent_memory tests
# Sort imports
isort agent_memory tests
# Type checking
mypy agent_memory
# Linting
flake8 agent_memory tests
Building for PyPI
# Build package
python -m build
# Upload to PyPI (requires API token)
python -m twine upload dist/*
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for new functionality
- Ensure all tests pass (
pytest) - Format code (
black .andisort .) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Changelog
v0.1.0 (Initial Release)
- Core memory management functionality
- SQLite and PostgreSQL support
- Memory types: conversation, preference, fact, context, goal, feedback
- Search and filtering capabilities
- Expiration and cleanup
- Comprehensive test suite
Support
- 📧 Email: your.email@example.com
- 🐛 Issues: GitHub Issues
- 💬 Discussions: GitHub Discussions
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file humem-0.1.0.tar.gz.
File metadata
- Download URL: humem-0.1.0.tar.gz
- Upload date:
- Size: 17.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.22
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7f0ac51c3abf5ee9c7b87015e2b152f2fb432d47674f9a3ce71094f28b0986fe
|
|
| MD5 |
228ddc0d74d9e0a8a7689a01815ba7a5
|
|
| BLAKE2b-256 |
27d6aaf7c96a280baab77c4180c7bf002d5b2cbdf6831265bfcb2cb0b5dd1aaf
|
File details
Details for the file humem-0.1.0-py3-none-any.whl.
File metadata
- Download URL: humem-0.1.0-py3-none-any.whl
- Upload date:
- Size: 12.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.22
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5c2548ecc6574375d666f4130f27a9c92120a5f37e7ef09b033c5b552860199c
|
|
| MD5 |
e63db94f54cc336bf838098fc28dbfb0
|
|
| BLAKE2b-256 |
9435ed592d07bb178699f3ddaf7887e16ff2ffeb2c9ed53ffec5a2f436dfe69d
|