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
Metadata
Release files for humem 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| humem-0.1.0.tar.gz | 17.0 kB | Without provenance | Details for humem-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| humem-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for humem-0.1.0-py3-none-any.whl |
Total release size: 30.0 kB
Release files / humem-0.1.0.tar.gz
| Download URL | humem-0.1.0.tar.gz |
|---|---|
| Size | 17.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7f0ac51c3abf5ee9c7b87015e2b152f2fb432d47674f9a3ce71094f28b0986fe
|
|
BLAKE2b-256 checksum How to use checksums |
27d6aaf7c96a280baab77c4180c7bf002d5b2cbdf6831265bfcb2cb0b5dd1aaf
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.9.22
|
Release files / humem-0.1.0-py3-none-any.whl
| Download URL | humem-0.1.0-py3-none-any.whl |
|---|---|
| Size | 12.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5c2548ecc6574375d666f4130f27a9c92120a5f37e7ef09b033c5b552860199c
|
|
BLAKE2b-256 checksum How to use checksums |
9435ed592d07bb178699f3ddaf7887e16ff2ffeb2c9ed53ffec5a2f436dfe69d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.9.22
|
Security for humem 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.