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 cortexdbai

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

pip install cortexdbai[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.5.tar.gz (26.5 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.5-py3-none-any.whl (23.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: cortexdbai-0.2.5.tar.gz
  • Upload date:
  • Size: 26.5 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.5.tar.gz
Algorithm Hash digest
SHA256 c2783ab2e4b9c9e0948fd405f9fc9491e27bbb29b15886b1316a22cda29a13f5
MD5 458b323165c342b789924a256d286d48
BLAKE2b-256 088016877efa6a8b8027b36144bdbb34a86cad04988eeaa1c742e989d1b3a62a

See more details on using hashes here.

File details

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

File metadata

  • Download URL: cortexdbai-0.2.5-py3-none-any.whl
  • Upload date:
  • Size: 23.8 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.5-py3-none-any.whl
Algorithm Hash digest
SHA256 dfd27373fb7f9464ddcff1b51992f4eb3c1279f2fc243dfb1f9a5cfc13bb0586
MD5 72ca0ce3117e97691674a8798eabf77e
BLAKE2b-256 3a3aa5d31acdc313a18b08eca22fe82725bea6e261d24c79d037110b12697d94

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