Metadata-Version: 2.4
Name: limbicdb
Version: 5.0.0
Summary: Production-grade AI memory infrastructure �?Python SDK with full parity to the TypeScript core.
Project-URL: Homepage, https://github.com/Kousoyu/limbicdb
Project-URL: Documentation, https://github.com/Kousoyu/limbicdb/tree/main/python
Project-URL: Repository, https://github.com/Kousoyu/limbicdb
Project-URL: Changelog, https://github.com/Kousoyu/limbicdb/blob/main/CHANGELOG.md
Author: Kousoyu
License: MIT
Keywords: agent,ai,langchain,llamaindex,memory,postgresql,sqlite,vector
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
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.10
Provides-Extra: async
Requires-Dist: aiosqlite>=0.20; extra == 'async'
Provides-Extra: dev
Requires-Dist: aiosqlite>=0.20; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.2; extra == 'langchain'
Provides-Extra: llamaindex
Requires-Dist: llama-index-core>=0.10; extra == 'llamaindex'
Provides-Extra: postgres
Requires-Dist: pgvector>=0.2; extra == 'postgres'
Requires-Dist: psycopg-pool>=3.2; extra == 'postgres'
Requires-Dist: psycopg[binary]>=3.1; extra == 'postgres'
Description-Content-Type: text/markdown

# LimbicDB Python SDK

[![CI](https://github.com/Kousoyu/limbicdb/actions/workflows/ci.yml/badge.svg)](https://github.com/Kousoyu/limbicdb/actions/workflows/ci.yml)
[![Python](https://img.shields.io/badge/python-%3E%3D3.10-3776ab?style=flat-square)](https://python.org)
[![License: MIT](https://img.shields.io/badge/license-MIT-a855f7?style=flat-square)](../LICENSE)

> **Production-grade AI memory infrastructure for Python.** Full feature parity with the TypeScript/Node.js core — same `.limbic` database files, identical cognitive scoring, native LangChain and LlamaIndex support.

---

## Features

| Feature | Status |
|---|---|
| **SQLite storage** — reads/writes `.limbic` files (cross-language compatible) | ✅ |
| **PostgreSQL + pgvector** — cloud/enterprise backend | ✅ |
| **ExplainEngine** — identical Ebbinghaus decay + ACT-R scoring to TS | ✅ |
| **HLC** — Hybrid Logical Clock for P2P sync | ✅ |
| **LangChain** — `LimbicChatMemory` + `LimbicVectorStore` | ✅ |
| **LlamaIndex** — `LimbicReader` + `LimbicQueryEngine` | ✅ |
| **pytest** — 53+ tests, 80% coverage gate | ✅ |
| **ruff** — zero lint errors | ✅ |

---

## Installation

```bash
# Core (SQLite only — zero extra deps)
pip install limbicdb

# With PostgreSQL + pgvector
pip install "limbicdb[postgres]"

# With LangChain
pip install "limbicdb[langchain]"

# With LlamaIndex
pip install "limbicdb[llamaindex]"

# Full
pip install "limbicdb[postgres,langchain,llamaindex]"
```

---

## Quick Start

```python
from limbicdb import open as ldb_open

db = ldb_open("./agent.limbic")

db.remember("User prefers dark mode")
db.remember("User is building an AI agent in Python", tags=["project", "ai"])

result = db.recall("Python AI preferences")
for memory in result.memories:
    print(memory.content)

# With full cognitive score explanation
result = db.recall("preferences", explain=True)
for memory in result.memories:
    print(f"[score={memory.explanation.score:.3f}] {memory.content}")
    print(f"  decay={memory.explanation.decay:.3f}")
    print(f"  repetition={memory.explanation.repetition:.3f}")

db.close()
```

## Context Manager

```python
with ldb_open("./agent.limbic") as db:
    db.remember("Context manager example")
    result = db.recall("Context manager")
    print(result.memories[0].content)
```

---

## PostgreSQL Backend

```python
from limbicdb import LimbicDB, LimbicDBConfig
from limbicdb.storage.postgres_store import PostgresStore

store = PostgresStore(
    conninfo="postgresql://postgres:password@localhost:5432/mydb",
    schema="agent_memory",
    embedding_dimensions=1536,
)
store.init()

db = LimbicDB(LimbicDBConfig(storage=store))
db.remember("Stored in PostgreSQL!")
db.close()
```

> Requires `pip install "limbicdb[postgres]"`

---

## LangChain Integration

### Chat Memory

```python
from limbicdb.integrations.langchain import LimbicChatMemory
from langchain.chains import ConversationChain
from langchain_openai import ChatOpenAI

memory = LimbicChatMemory(
    path="./chat.limbic",
    session_id="user-42",
    max_history=20,
)

chain = ConversationChain(llm=ChatOpenAI(), memory=memory)
response = chain.invoke({"input": "Hello, my name is Alice"})
```

### RAG Vector Store

```python
from limbicdb.integrations.langchain import LimbicVectorStore

store = LimbicVectorStore(path="./knowledge.limbic")
store.add_texts(["LimbicDB uses Ebbinghaus decay", "Python SDK supports PostgreSQL"])

retriever = store.as_retriever(k=5)
# Use retriever in any LangChain RetrievalQA chain
```

---

## LlamaIndex Integration

```python
from limbicdb.integrations.llamaindex import LimbicQueryEngine

engine = LimbicQueryEngine(path="./agent.limbic", top_k=5)
response = engine.query("UI preferences")
print(response.response)
print(response.source_nodes)

# Or as a Reader for VectorStoreIndex
from limbicdb.integrations.llamaindex import LimbicReader
from llama_index.core import VectorStoreIndex

nodes = LimbicReader(path="./agent.limbic").load_data()
index = VectorStoreIndex(nodes)
```

---

## Cross-Language Interoperability

The Python SDK reads and writes the **exact same `.limbic` format** as the TypeScript/Node.js core:

```python
# Python writes
with ldb_open("./shared.limbic") as db:
    db.remember("Written by Python!")

# Node.js reads (TypeScript):
# const db = open('./shared.limbic')
# const result = await db.recall('Python')
# → "Written by Python!"
```

Enables polyglot Agent architectures:
```
FastAPI (Python) ←── .limbic ──→ Next.js (TypeScript)
```

---

## ExplainEngine — Score Formula

| Component | Formula | Weight |
|---|---|---|
| **Semantic** | Cosine similarity | 50% |
| **Decay** | Ebbinghaus `exp(-t/S)` | 30% |
| **Repetition** | Pimsleur sigmoid over `access_count` | 15% |
| **Recency** | `exp(-elapsed_days/7)` | 5% |

Weights are **identical** to the TypeScript `ExplainEngine` — cross-language score parity guaranteed.

---

## Running Tests

```bash
cd python

uv sync --extra dev

# Unit tests (no PostgreSQL)
uv run pytest tests/test_core.py tests/test_hlc.py tests/test_integrations.py -v

# PostgreSQL integration tests
PG_TEST_URL=postgres://postgres:password@localhost:5432/testdb \
  uv run pytest tests/test_postgres.py -v

# Lint + type check
uv run ruff check src/
uv run mypy src/
```

---

## Project Layout

```
python/
├── pyproject.toml
├── src/limbicdb/
│   ├── types.py                  # Memory, Session, MemoryKind, …
│   ├── open.py                   # Convenience open() function
│   ├── core/
│   │   ├── limbicdb.py           # LimbicDB (remember/recall/forget)
│   │   └── explain_engine.py     # ExplainEngine (Ebbinghaus + ACT-R)
│   ├── storage/
│   │   ├── interface.py          # IStorage Protocol
│   │   ├── sqlite_adapter.py     # SQLiteStorageAdapter
│   │   ├── memory_adapter.py     # MemoryStorageAdapter (tests)
│   │   └── postgres_store.py     # PostgresStore (psycopg3 + pgvector)
│   ├── sync/
│   │   └── hlc.py                # HybridLogicalClock
│   └── integrations/
│       ├── langchain.py          # LimbicChatMemory + LimbicVectorStore
│       └── llamaindex.py         # LimbicReader + LimbicQueryEngine
└── tests/
    ├── test_core.py              # 20 core + interop tests
    ├── test_hlc.py               # 12 HLC tests
    ├── test_integrations.py      # 21 LangChain + LlamaIndex tests
    └── test_postgres.py          # 8 PostgreSQL integration tests
```

---

## License

MIT © [Kousoyu](https://github.com/Kousoyu)
