AI agent memory SDK built on Convex - ACID storage, vector search, and conversation management
Project description
Cortex Python SDK
Native Python SDK for AI agent memory, powered by Convex
๐ Quick Start
Installation
# Basic installation
pip install cortex-memory
# With graph database support
pip install "cortex-memory[graph]"
# With A2A communication support
pip install "cortex-memory[a2a]"
# With all optional dependencies
pip install "cortex-memory[all]"
# Development installation
pip install "cortex-memory[dev]"
Install from source:
git clone https://github.com/SaintNick1214/Project-Cortex.git
cd Project-Cortex/cortex-sdk-python
pip install -e ".[dev]"
Your First Memory
import asyncio
from cortex import Cortex, CortexConfig, RememberParams
async def main():
# Initialize Cortex
cortex = Cortex(CortexConfig(
convex_url="https://your-deployment.convex.cloud"
))
# Remember a conversation
result = await cortex.memory.remember(
RememberParams(
memory_space_id="my-agent",
conversation_id="conv-1",
user_message="I prefer dark mode",
agent_response="Got it! I'll remember that.",
user_id="user-123",
user_name="User"
)
)
# Search your memories
results = await cortex.memory.search(
"my-agent",
"what are the user's preferences?"
)
for memory in results:
print(f"Found: {memory.content}")
# Clean up
await cortex.close()
# Run
asyncio.run(main())
โจ Features
The Python SDK provides 100% API compatibility with the TypeScript SDK:
- ๐ง Flexible Memory - Remember anything without hardcoded schemas
- ๐ Memory Space Isolation - Flexible boundaries (per user, team, or project)
- โพ๏ธ Long-term Persistence - Memories last forever with automatic indexing
- โฑ๏ธ Automatic Versioning - Updates preserve history, never lose data
- ๐๏ธ ACID + Vector Hybrid - Immutable conversation source + fast searchable index
- ๐ Semantic Search - AI-powered retrieval with embeddings
- ๐ Context Chains - Hierarchical context sharing across agents
- ๐ฅ User Profiles - Rich user context with GDPR cascade deletion
- ๐ Facts Layer - Extract structured knowledge for 60-90% storage savings
- ๐ธ๏ธ Graph Integration - Optional Neo4j/Memgraph support
- ๐ค A2A Communication - Agent-to-agent messaging helpers
- ๐ Access Analytics - Built-in statistics and insights
- ๐ก๏ธ Governance Policies - Centralized data retention, purging, and compliance (GDPR, HIPAA, SOC2, FINRA)
- ๐ Resilience Layer - Rate limiting, circuit breaker, priority queue for overload protection
โจ What's New in v0.16.0
Resilience Layer - Production-Ready Overload Protection
NEW: Built-in protection against server overload during extreme traffic bursts:
from cortex import Cortex, CortexConfig
from cortex.resilience import ResiliencePresets
# Default - enabled with balanced settings (no config needed!)
cortex = Cortex(CortexConfig(convex_url=os.getenv("CONVEX_URL")))
# Or use a preset for your use case
realtime_cortex = Cortex(CortexConfig(
convex_url=os.getenv("CONVEX_URL"),
resilience=ResiliencePresets.real_time_agent, # Low latency
))
# Monitor health
print(cortex.is_healthy()) # False if circuit is open
print(cortex.get_resilience_metrics()) # Full metrics
# Graceful shutdown
await cortex.shutdown(timeout_s=30.0) # Wait for pending ops
Features:
- โก Token Bucket Rate Limiter - Smooths bursty traffic
- ๐ฆ Concurrency Limiter - Controls parallel requests
- ๐ฏ Priority Queue - Critical ops get priority
- ๐ Circuit Breaker - Fails fast when backend is unhealthy
๐๏ธ Architecture
Cortex uses a 4-layer architecture:
Layer 1: ACID Stores (Source of Truth)
โโโ 1a: Conversations (memory-space-scoped)
โโโ 1b: Immutable (truly shared - KB, policies)
โโโ 1c: Mutable (truly shared - config, inventory)
Layer 2: Vector Index (memory-space-scoped, searchable)
โโโ Embedded memories for semantic search
Layer 3: Facts Store (memory-space-scoped, versioned)
โโโ LLM-extracted facts, 60-90% token savings
Layer 4: Convenience APIs (wrapper over L1-3)
โโโ Primary developer interface
๐ Usage Examples
Basic Memory Operations
from cortex import Cortex, CortexConfig, RememberParams, SearchOptions
# Initialize
cortex = Cortex(CortexConfig(convex_url=os.getenv("CONVEX_URL")))
# Remember
result = await cortex.memory.remember(
RememberParams(
memory_space_id="agent-1",
conversation_id="conv-123",
user_message="My password is Blue123",
agent_response="I'll remember that securely!",
user_id="user-123",
user_name="Alex",
importance=100,
tags=["password", "security"]
)
)
# Search
memories = await cortex.memory.search(
"agent-1",
"user password",
SearchOptions(
user_id="user-123",
min_importance=70,
limit=10
)
)
# Update
await cortex.memory.update(
"agent-1",
memory_id,
{"content": "Password updated", "importance": 100}
)
# Delete
await cortex.memory.delete("agent-1", memory_id)
User Profiles & GDPR
from cortex import DeleteUserOptions
# Create/update user profile
user = await cortex.users.update(
"user-123",
{
"displayName": "Alex Johnson",
"email": "alex@example.com",
"preferences": {"theme": "dark"}
}
)
# GDPR cascade deletion (deletes across ALL layers)
result = await cortex.users.delete(
"user-123",
DeleteUserOptions(cascade=True, verify=True)
)
print(f"Deleted {result.total_deleted} records")
print(f"Layers affected: {', '.join(result.deleted_layers)}")
Graph Integration
from cortex import CortexConfig, GraphConfig, GraphConnectionConfig
from cortex.graph import CypherGraphAdapter, initialize_graph_schema
# Setup graph adapter
graph = CypherGraphAdapter()
await graph.connect(
GraphConnectionConfig(
uri="bolt://localhost:7687",
username="neo4j",
password="password"
)
)
# Initialize schema
await initialize_graph_schema(graph)
# Initialize Cortex with graph
cortex = Cortex(
CortexConfig(
convex_url=os.getenv("CONVEX_URL"),
graph=GraphConfig(adapter=graph, auto_sync=True)
)
)
# Use normally - auto-syncs to graph!
await cortex.memory.remember(params)
Multi-Agent Coordination
from cortex import ContextInput, A2ASendParams
# Create workflow context
context = await cortex.contexts.create(
ContextInput(
purpose="Process refund request",
memory_space_id="supervisor-space",
user_id="user-123",
data={"amount": 500, "importance": 85}
)
)
# Send A2A message
await cortex.a2a.send(
A2ASendParams(
from_agent="supervisor-agent",
to_agent="finance-agent",
message="Please approve $500 refund",
user_id="user-123",
context_id=context.id,
importance=85
)
)
๐ Migration from TypeScript
The Python SDK maintains API compatibility with the TypeScript SDK. Here's how to translate:
TypeScript:
const cortex = new Cortex({ convexUrl: process.env.CONVEX_URL });
const result = await cortex.memory.remember({
memorySpaceId: "agent-1",
conversationId: "conv-123",
userMessage: "I prefer dark mode",
agentResponse: "Got it!",
userId: "user-123",
userName: "Alex",
importance: 70,
tags: ["preferences"],
});
Python:
cortex = Cortex(CortexConfig(convex_url=os.getenv("CONVEX_URL")))
result = await cortex.memory.remember(
RememberParams(
memory_space_id="agent-1",
conversation_id="conv-123",
user_message="I prefer dark mode",
agent_response="Got it!",
user_id="user-123",
user_name="Alex",
importance=70,
tags=["preferences"]
)
)
Key Differences:
- camelCase โ snake_case for parameters and methods
- Objects โ dataclasses or named parameters
- Same structure, same capabilities, native Python
๐ API Reference
All TypeScript APIs are available in Python:
| API Module | Description | Methods |
|---|---|---|
cortex.memory.* |
Layer 4: Memory convenience API | 14 methods |
cortex.conversations.* |
Layer 1a: ACID conversations | 13 methods |
cortex.immutable.* |
Layer 1b: Shared immutable data | 9 methods |
cortex.mutable.* |
Layer 1c: Shared mutable data | 12 methods |
cortex.vector.* |
Layer 2: Vector index | 13 methods |
cortex.facts.* |
Layer 3: Facts store | 10 methods |
cortex.contexts.* |
Coordination: Context chains | 17 methods |
cortex.users.* |
Coordination: User profiles + GDPR | 11 methods |
cortex.agents.* |
Coordination: Agent registry | 8 methods |
cortex.memory_spaces.* |
Coordination: Memory spaces | 9 methods |
cortex.a2a.* |
Helpers: A2A communication | 4 methods |
cortex.graph.* |
Graph database integration | ~20 methods |
Total: ~140 methods - Full feature parity with TypeScript SDK!
๐งช Testing
# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run with coverage
pytest --cov=cortex --cov-report=html
# Run specific test
pytest tests/test_memory.py -v
๐ Documentation
Quick Links
- START HERE - Navigation guide for all documentation
- Developer Guide - Comprehensive Python guide
- Migration Guide - TypeScript to Python migration
- Testing Guide - How to test the SDK
- Examples - 4 working applications
Shared Documentation
- API Reference - Complete API documentation
- Core Features - Feature guides
- Architecture - System architecture
- Advanced Topics - Graph DB, facts, etc.
๐ Requirements
- Python 3.12 or 3.13 (tested on both versions)
- Convex backend running (local, cloud, or self-hosted)
- Use existing
.env.localconfiguration - LOCAL:
npm run dev:localfrom project root - MANAGED: Already running at https://expert-buffalo-268.convex.cloud
- Use existing
Optional:
- Neo4j or Memgraph (for graph integration)
- Redis (for A2A pub/sub)
๐งช Testing
The Python SDK has full dual-testing infrastructure (identical to TypeScript SDK):
Quick Test Commands (mirrors TypeScript SDK)
# Auto-detect and run appropriate suite(s) - like "npm test"
make test
# Run LOCAL tests only - like "npm run test:local"
make test-local
# Run MANAGED tests only - like "npm run test:managed"
make test-managed
# Explicitly run BOTH suites - like "npm run test:both"
make test-both
Alternative: Direct Script Usage
# Auto-detect (runs BOTH if both configs present)
python scripts/run-python-tests.py
# Explicit modes
python scripts/run-python-tests.py --mode=local
python scripts/run-python-tests.py --mode=managed
python scripts/run-python-tests.py --mode=both
Raw pytest (single suite only)
# Runs one suite based on auto-detection (defaults to LOCAL if both present)
pytest tests/ -v
# With explicit mode
CONVEX_TEST_MODE=local pytest tests/ -v
CONVEX_TEST_MODE=managed pytest tests/ -v
Test Coverage
- 579 tests covering all APIs (includes 5 OpenAI tests that skip in CI)
- 73% code coverage (actively increasing)
- 100% pass rate on both local and managed environments
- OpenAI tests run locally with OPENAI_API_KEY, skip in CI (too expensive)
Test Environments
| Environment | Features | Speed | Use Case |
|---|---|---|---|
| LOCAL | โ ACID, โ Vector search | โก 2-3 min | Fast iteration |
| MANAGED | โ ACID, โ Vector search | ๐ 15 min | Full validation |
Note: Both SDKs now include 5 OpenAI integration tests (skipped without OPENAI_API_KEY).
๐ค Contributing
We welcome contributions! The Python SDK follows the same architecture as the TypeScript SDK.
See CONTRIBUTING.md for guidelines.
๐ License
Apache License 2.0 - Same as the TypeScript SDK
- Free for commercial use
- Explicit patent grant and protection
- See LICENSE.md for details
๐ Acknowledgments
- Convex - The reactive backend platform
- TypeScript SDK - This Python port maintains full compatibility
- The open source AI community
๐ฎ Support
- ๐ง Email: support@cortexmemory.dev
- ๐ฌ Discussions: GitHub Discussions
- ๐ Issues: GitHub Issues
- ๐ Docs: Documentation
Built with โค๏ธ for the AI agent community
Python port by Saint Nick LLC | Original SDK by Nicholas Geil
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 cortex_memory-0.23.0.tar.gz.
File metadata
- Download URL: cortex_memory-0.23.0.tar.gz
- Upload date:
- Size: 261.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dbc916648cbefaa20d5fb80e214985a006fbe6c098fdf3aae9b598e4092d61aa
|
|
| MD5 |
1e4e1c00b22078441a332d12593e1ca7
|
|
| BLAKE2b-256 |
b06283dc2ddb2ee1a7890fea58f87e6275bca12a3ce99197562eb6d5698eb0da
|
Provenance
The following attestation bundles were made for cortex_memory-0.23.0.tar.gz:
Publisher:
publish.yml on SaintNick1214/Project-Cortex
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
cortex_memory-0.23.0.tar.gz -
Subject digest:
dbc916648cbefaa20d5fb80e214985a006fbe6c098fdf3aae9b598e4092d61aa - Sigstore transparency entry: 773968487
- Sigstore integration time:
-
Permalink:
SaintNick1214/Project-Cortex@978bbe7a250322f05e892dc4852f656c505e003b -
Branch / Tag:
refs/heads/main - Owner: https://github.com/SaintNick1214
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@978bbe7a250322f05e892dc4852f656c505e003b -
Trigger Event:
push
-
Statement type:
File details
Details for the file cortex_memory-0.23.0-py3-none-any.whl.
File metadata
- Download URL: cortex_memory-0.23.0-py3-none-any.whl
- Upload date:
- Size: 248.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3c4264753ab5122620cfcf8bcc8fd666caf231843748aa705558605119f34e89
|
|
| MD5 |
186e9d1c8240759cfc0f3494798c2e45
|
|
| BLAKE2b-256 |
ed310537e251479ea40333d619b4fef0261e973a29a89b6571efb0854a33481a
|
Provenance
The following attestation bundles were made for cortex_memory-0.23.0-py3-none-any.whl:
Publisher:
publish.yml on SaintNick1214/Project-Cortex
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
cortex_memory-0.23.0-py3-none-any.whl -
Subject digest:
3c4264753ab5122620cfcf8bcc8fd666caf231843748aa705558605119f34e89 - Sigstore transparency entry: 773968491
- Sigstore integration time:
-
Permalink:
SaintNick1214/Project-Cortex@978bbe7a250322f05e892dc4852f656c505e003b -
Branch / Tag:
refs/heads/main - Owner: https://github.com/SaintNick1214
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@978bbe7a250322f05e892dc4852f656c505e003b -
Trigger Event:
push
-
Statement type: