Metadata-Version: 2.4
Name: cortexdbai
Version: 0.2.3
Summary: The Long-Term Memory Layer for AI Systems
Project-URL: Homepage, https://cortexdb.ai
Project-URL: Documentation, https://docs.cortexdb.ai
Project-URL: Repository, https://github.com/cortexdb/cortexdb
Project-URL: Issues, https://github.com/cortexdb/cortexdb/issues
Project-URL: Changelog, https://github.com/cortexdb/cortexdb/blob/main/CHANGELOG.md
Author-email: Prashant Malik <prashant@cortexdb.ai>
License-Expression: Apache-2.0
Keywords: ai,cortexdb,event-sourcing,knowledge-graph,llm,memory
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx>=0.24
Requires-Dist: pydantic>=2.0
Requires-Dist: requests>=2.31
Requires-Dist: tenacity>=8.0
Provides-Extra: async
Requires-Dist: httpx[http2]; extra == 'async'
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.4; extra == 'dev'
Description-Content-Type: text/markdown

# 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](https://img.shields.io/pypi/v/cortexdb.svg)](https://pypi.org/project/cortexdbai/)
[![Python](https://img.shields.io/pypi/pyversions/cortexdb.svg)](https://pypi.org/project/cortexdbai/)
[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/cortexdb/cortexdb/blob/main/LICENSE)

## Installation

```bash
pip install cortexdbai
```

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

```bash
pip install cortexdbai[async]
```

## Quick Start

```python
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`:

```python
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:

```python
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:

```python
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:

```python
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:

```python
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

- [Documentation](https://docs.cortexdb.ai)
- [GitHub Repository](https://github.com/cortexdb/cortexdb)
- [Issue Tracker](https://github.com/cortexdb/cortexdb/issues)
- [Changelog](https://github.com/cortexdb/cortexdb/blob/main/CHANGELOG.md)

## License

Apache-2.0
