Skip to main content

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

License: Apache 2.0 Python 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

Shared Documentation

๐Ÿ”’ Requirements

  • Python 3.12 or 3.13 (tested on both versions)
  • Convex backend running (local, cloud, or self-hosted)

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


Built with โค๏ธ for the AI agent community

Python port by Saint Nick LLC | Original SDK by Nicholas Geil

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cortex_memory-0.23.0.tar.gz (261.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cortex_memory-0.23.0-py3-none-any.whl (248.6 kB view details)

Uploaded Python 3

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

Hashes for cortex_memory-0.23.0.tar.gz
Algorithm Hash digest
SHA256 dbc916648cbefaa20d5fb80e214985a006fbe6c098fdf3aae9b598e4092d61aa
MD5 1e4e1c00b22078441a332d12593e1ca7
BLAKE2b-256 b06283dc2ddb2ee1a7890fea58f87e6275bca12a3ce99197562eb6d5698eb0da

See more details on using hashes here.

Provenance

The following attestation bundles were made for cortex_memory-0.23.0.tar.gz:

Publisher: publish.yml on SaintNick1214/Project-Cortex

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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

Hashes for cortex_memory-0.23.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3c4264753ab5122620cfcf8bcc8fd666caf231843748aa705558605119f34e89
MD5 186e9d1c8240759cfc0f3494798c2e45
BLAKE2b-256 ed310537e251479ea40333d619b4fef0261e973a29a89b6571efb0854a33481a

See more details on using hashes here.

Provenance

The following attestation bundles were made for cortex_memory-0.23.0-py3-none-any.whl:

Publisher: publish.yml on SaintNick1214/Project-Cortex

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page