Skip to main content

The Long-Term Memory Layer for AI Systems

Project description

CortexDB Python SDK

The Long-Term Memory Layer for AI Systems.

CortexDB gives your AI agents persistent, searchable memory. Store conversations, decisions, incidents, and domain knowledge as structured episodes. Retrieve relevant context with a single call.

PyPI version Python License

Installation

pip install cortexdb

For HTTP/2 support (recommended for async workloads):

pip install cortexdb[async]

Quick Start

from cortexdb import Cortex

# Connect to CortexDB
cortex = Cortex("http://localhost:3141", api_key="your-api-key")

# Remember something
cortex.remember("The payments service was migrated to Kubernetes on March 15th.")

# Recall relevant memories
result = cortex.recall("When did we migrate payments?")
for match in result.matches:
    print(f"[{match.confidence:.0%}] {match.content}")

# Forget when needed (GDPR, cleanup, etc.)
cortex.forget(query="old deploy logs", reason="quarterly cleanup")

# Search with filters
results = cortex.search(
    "deploy failure",
    source="github",
    time_range="7d",
    limit=10,
)
print(results.context)

Async Usage

Every method has an async counterpart via AsyncCortex:

import asyncio
from cortexdb import AsyncCortex

async def main():
    async with AsyncCortex("http://localhost:3141", api_key="your-api-key") as cortex:
        await cortex.remember("Async memory storage works great.")

        result = await cortex.recall("How does async work?")
        for match in result.matches:
            print(match.content)

asyncio.run(main())

Episode Ingestion

For structured data, use episodes with full metadata:

from cortexdb import Cortex, IngestEpisodeRequest, Actor, Source, ActorType, EpisodeType

cortex = Cortex("http://localhost:3141")

# Ingest a structured episode
episode = IngestEpisodeRequest(
    content="PR #412: Add retry logic to payment processor",
    episode_type=EpisodeType.CODE_CHANGE,
    actor=Actor(id="ci-bot", name="CI Bot", actor_type=ActorType.SERVICE),
    source=Source(connector="github", external_id="pr-412", url="https://github.com/org/repo/pull/412"),
    metadata={"branch": "main", "files_changed": 3},
)
response = cortex.ingest_episode(episode)
print(f"Episode {response.episode_id} ingested.")

# Or use the smart store shorthand
cortex.store("Plain text goes through remember().")
cortex.store({
    "content": "Dict data goes through ingest_episode().",
    "type": "deployment",
    "source": "slack",
})

Entity Lookup

Explore entities and their relationships in the knowledge graph:

cortex = Cortex("http://localhost:3141")

# Look up an entity
entity = cortex.entity("payments-service")
print(f"{entity.name} ({entity.entity_type})")
print(f"  Episodes: {entity.episode_count}")
print(f"  First seen: {entity.first_seen}")

# Browse relationships
for rel in entity.relationships:
    print(f"  {rel.relationship} -> {rel.target_entity_id} ({rel.confidence:.0%})")

# Create explicit relationships
cortex.link(
    source_entity_id="payments-service",
    target_entity_id="auth-service",
    relationship="DEPENDS_ON",
    fact="Payments calls auth for token validation",
    confidence=0.95,
)

Error Handling

The SDK provides a structured exception hierarchy:

from cortexdb import Cortex
from cortexdb.exceptions import (
    CortexError,          # Base exception
    CortexAPIError,       # HTTP 4xx/5xx errors
    CortexAuthError,      # HTTP 401/403
    CortexRateLimitError, # HTTP 429 (includes retry_after)
    CortexConnectionError,# Network failures
    CortexTimeoutError,   # Request timeouts
)

cortex = Cortex("http://localhost:3141")

try:
    cortex.remember("important data")
except CortexRateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after}s")
except CortexAuthError as e:
    print(f"Authentication failed: {e.message}")
except CortexConnectionError:
    print("Cannot reach CortexDB server")
except CortexAPIError as e:
    print(f"API error [{e.status_code}]: {e.message}")

Transient errors (429, 502, 503, 504) and connection failures are automatically retried with exponential backoff. Configure retry behavior at client initialization:

cortex = Cortex(
    "http://localhost:3141",
    max_retries=5,   # default: 3
    timeout=60.0,    # default: 30.0 seconds
)

Configuration

Constructor Parameters

Parameter Type Default Description
base_url str http://localhost:3141 CortexDB server URL
api_key str None Bearer token for authentication
timeout float 30.0 Request timeout in seconds
max_retries int 3 Max retries for transient failures

Environment Variables

Variable Description
CORTEXDB_API_KEY Fallback API key when none is passed directly

Convenience Methods

Method Description
cortex.memory(q) Alias for recall() -- the GTM one-liner
cortex.store(data) Smart dispatch: str -> remember(), dict -> ingest_episode()
cortex.context(q) Recall with higher token budget (8192) for LLM agents

Links

License

Apache-2.0

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

cortexdbai-0.2.0.tar.gz (16.4 kB view details)

Uploaded Source

Built Distribution

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

cortexdbai-0.2.0-py3-none-any.whl (13.5 kB view details)

Uploaded Python 3

File details

Details for the file cortexdbai-0.2.0.tar.gz.

File metadata

  • Download URL: cortexdbai-0.2.0.tar.gz
  • Upload date:
  • Size: 16.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.11

File hashes

Hashes for cortexdbai-0.2.0.tar.gz
Algorithm Hash digest
SHA256 638da4f68a76223e8f16a84fa07ca1467bed8e358b0ed1b92e97765e08ad8e0f
MD5 794bef24eea509d35414c00dc8e5cb42
BLAKE2b-256 bad79d7350dc34744d747270d15876a08c870e463b8aec5849a07b4a732c03de

See more details on using hashes here.

File details

Details for the file cortexdbai-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: cortexdbai-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 13.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.11

File hashes

Hashes for cortexdbai-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 48afecfa33d27688b147f5441a208291495e9e4d712d34e81183d6f0702764f7
MD5 70e9986ccc8c2d7261c083492994ad90
BLAKE2b-256 a13674ab6bfc0cc34b0e5dfcbe26461f6c0a9cc37c4a81b995ecd237d65bb174

See more details on using hashes here.

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