Metadata-Version: 2.4
Name: ouroboros-memory
Version: 1.0.0
Summary: Lifelong, contradiction-aware, curiosity-driven memory infrastructure for large language models. Local-first, LLM-agnostic, symbolic.
Project-URL: Homepage, https://github.com/Open-ouroboros/ouroboros-memory
Project-URL: Documentation, https://ouroboros-memory.readthedocs.io
Project-URL: Repository, https://github.com/Open-ouroboros/ouroboros-memory
Project-URL: Issues, https://github.com/Open-ouroboros/ouroboros-memory/issues
Project-URL: Changelog, https://github.com/Open-ouroboros/ouroboros-memory/blob/main/CHANGELOG.md
Project-URL: Discussions, https://github.com/Open-ouroboros/ouroboros-memory/discussions
Author: Ouroboros Research Collective
Author-email: Sandesh Bastola <sandeshbastola19@gmail.com>
License: Apache-2.0
License-File: LICENSE
Keywords: agent,ai,knowledge-graph,llm,local-first,memory,neuro-symbolic,privacy,rag,symbolic
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
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 :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: anthropic>=0.28.0
Requires-Dist: cryptography>=42.0.0
Requires-Dist: fastapi>=0.110.0
Requires-Dist: google-generativeai>=0.5.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: llama-cpp-python>=0.2.70; platform_machine != 'arm64' or sys_platform != 'darwin'
Requires-Dist: openai>=1.30.0
Requires-Dist: platformdirs>=4.2.0
Requires-Dist: pydantic>=2.6.0
Requires-Dist: python-multipart>=0.0.9
Requires-Dist: pyyaml>=6.0
Requires-Dist: rich>=13.7.0
Requires-Dist: typer>=0.12.0
Requires-Dist: uvicorn[standard]>=0.27.0
Requires-Dist: watchfiles>=0.21.0
Requires-Dist: websockets>=12.0
Provides-Extra: all
Requires-Dist: ouroboros-digikabaz[ner]; extra == 'all'
Requires-Dist: spacy>=3.7.0; extra == 'all'
Provides-Extra: dev
Requires-Dist: hatch>=1.9.0; extra == 'dev'
Requires-Dist: ipython>=8.20.0; extra == 'dev'
Requires-Dist: mypy>=1.8.0; extra == 'dev'
Requires-Dist: pre-commit>=3.6.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.1.0; extra == 'dev'
Requires-Dist: pytest-mock>=3.12.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: respx>=0.21.0; extra == 'dev'
Requires-Dist: ruff>=0.3.0; extra == 'dev'
Requires-Dist: types-pyyaml; extra == 'dev'
Requires-Dist: types-requests; extra == 'dev'
Provides-Extra: gui
Provides-Extra: privacy
Requires-Dist: ouroboros-digikabaz>=0.1.0; extra == 'privacy'
Description-Content-Type: text/markdown

# Ouroboros Memory

> *"The LLM is the voice. Ouroboros is the mind."*

**Symbolic, contradiction-aware, lifelong memory infrastructure for large language models.**

Ouroboros Memory is a production-ready local-first system that brings **persistent, coherent, auditable memory** to any LLM. Unlike embeddings-based approaches, it uses transparent symbolic knowledge graphs that detect contradictions, infer missing facts, and organize autonomously—without cloud lock-in or GPU requirements.

[![PyPI](https://img.shields.io/pypi/v/ouroboros-memory?style=flat-square)](https://pypi.org/project/ouroboros-memory/)
[![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue?style=flat-square)](https://www.python.org/)
[![License Apache 2.0](https://img.shields.io/badge/license-Apache--2.0-blue?style=flat-square)](LICENSE)
[![Tests Passing](https://img.shields.io/badge/tests-85%2B%20passing-brightgreen?style=flat-square)](tests/)
[![Coverage](https://img.shields.io/badge/coverage-88.79%25-brightgreen?style=flat-square)](tests/)

---

## The Problem

Current LLMs suffer from **three critical memory failures**:

| Problem | Impact |
|---------|--------|
| **No persistent memory** | Each conversation starts blank. Context windows can't hold real history. |
| **No contradiction detection** | Conflicting information silently overwrites; coherence degrades over time. |
| **Cloud lock-in** | Embeddings/vectors require expensive APIs; local alternatives are unauditable. |

**Ouroboros solves all three:** persistent symbolic memory, contradiction detection, full auditability, runs on consumer hardware.

---

## Key Features

✨ **Symbolic Knowledge Graph**
- Transparent `(subject, relation, object)` triples with confidence weights
- No opaque embeddings—every fact is human-readable and auditable
- Contradictions detected and flagged, never silently blended

🧠 **Curiosity-Driven Autonomous Learning**
- Automatic tension detection: contradictions, prediction errors, novelty, information gaps
- System autonomously formulates clarifying questions
- Self-organizing fact consolidation and reorganization

🔌 **LLM-Agnostic**
- Drop-in support for 6 providers: Ollama, llama.cpp, vLLM, OpenAI, Anthropic, Google Gemini
- Switch providers without losing a single memory
- Identical API across all backends

💻 **Local-First**
- Runs on laptops and consumer hardware
- No GPU required for the memory layer
- Optional local LLM support (Ollama, llama.cpp) for fully offline operation

🔐 **Privacy-Respecting**
- Optional 5-level privacy bridge (PII tokenization, synthetic noise injection, cloud-disable mode)
- Powered by [DigiKabaz](https://github.com/Open-ouroboros/ouroboros-digikabaz)
- All privacy layers are transparent and configurable

📊 **Production Ready**
- **88.79% test coverage** (85+ passing tests across core, llm, api, cli, storage, privacy)
- **Strict code quality**: ruff linting + mypy --strict type checking
- **Proven scalability**: 1M-fact benchmarks with constant throughput (29,469 facts/sec)
- **Paper-conformant**: 28 architecture claims validated against empirical data

---

## 30-Second Example

```python
from ouroboros import OuroborosMind

# Create a mind (first-run wizard writes ~/.ouroboros/config.yaml)
mind = OuroborosMind()

# Add a fact
mind.chat("My name is Tony. I like dark mode.")
# → "Noted, Tony. I have crystallized your preference for dark mode."

# Switch LLM provider (memory transfers instantly)
mind.switch_llm("openai", "gpt-4o")

# Query the memory
mind.chat("What do I like?")
# → "Based on my memory, you enjoy dark mode, Tony."

# Inspect what was stored
print(mind.crystal.facts)
# → [Fact(subject='Tony', relation='has_name', object='Tony', confidence=1.0),
#     Fact(subject='Tony', relation='prefers', object='dark mode', confidence=0.95)]
```

---

## Installation

### PyPI (Recommended)

```bash
pip install ouroboros-memory
```

### From Source

```bash
git clone https://github.com/Open-ouroboros/ouroboros-memory
cd ouroboros-memory
pip install -e .[dev,all]
```

### LLM Setup

By default, Ouroboros uses **Ollama** with `gemma3:4b-cloud`. No setup needed; the app will guide you.

To use OpenAI, Anthropic, or other providers:

```bash
# Configure via interactive setup
ouroboros config

# Or edit directly
nano ~/.ouroboros/config.yaml
```

---

## Architecture at a Glance

```
┌─────────────────────────────────────────────────────┐
│  LLM Agent (OpenAI · Anthropic · Ollama · etc.)    │
└────────────────┬────────────────────────────────────┘
                 │ System Prompt + Injected Facts
                 ▼
┌─────────────────────────────────────────────────────┐
│             8-Step Chat Pipeline                    │
│  Query Analysis → Crystal Ranker → Context Inject   │
│       → LLM Response → Fact Extract → Tension       │
│           Detection → Infer → Consolidate           │
└────────────────┬────────────────────────────────────┘
                 │
        ┌────────┼────────┐
        ▼        ▼        ▼
    ┌────────────────────────────────────────────────┐
    │        Ouroboros Memory Core                  │
    │  ┌─────────────────────────────────────────┐  │
    │  │  Crystal (Dual-layer Knowledge Graph)   │  │
    │  │  • 28 semantic relation types            │  │
    │  │  • Contradiction detection               │  │
    │  │  • Fact confidence tracking              │  │
    │  └─────────────────────────────────────────┘  │
    │  ┌─────────────────────────────────────────┐  │
    │  │  Resonance (Dynamic Attention Field)    │  │
    │  │  • 24→120 dimensional embedding space   │  │
    │  │  • Concept ranking and relevance        │  │
    │  │  • O(1) query performance                │  │
    │  └─────────────────────────────────────────┘  │
    │  ┌─────────────────────────────────────────┐  │
    │  │  Tension Engine (Curiosity System)      │  │
    │  │  • 7 tension types (contradictions,     │  │
    │  │    prediction errors, novelty, gaps)    │  │
    │  │  • Autonomous question formulation      │  │
    │  │  • Self-directed learning               │  │
    │  └─────────────────────────────────────────┘  │
    │  ┌─────────────────────────────────────────┐  │
    │  │  Storage Backend (PostgreSQL, SQLite)   │  │
    │  │  • Persistent fact storage              │  │
    │  │  • Scalable to millions of facts        │  │
    │  │  • ACID transactions                    │  │
    │  └─────────────────────────────────────────┘  │
    └────────────────────────────────────────────────┘
```

**Full architectural detail:** [docs/architecture.md](./docs/architecture.md)

---

## Privacy & Security

Ouroboros integrates **DigiKabaz**, a privacy bridge with five graduated levels:

| Level | Description |
|-------|-------------|
| **1 (None)** | Memory sent to cloud as-is (default for local-only LLMs) |
| **2 (Minimal)** | Regex PII (email, phone, SSN) tokenized before cloud transmission |
| **3 (Balanced, default)** | Names, companies, locations, financial data, health info tokenized |
| **4 (High)** | All personal facts tokenized + synthetic noise injection |
| **5 (Maximum)** | Cloud LLMs disabled entirely; local models only |

**Transparent, configurable, auditable.** No hidden encryption; you control exactly what leaves your device.

---

## Getting Started

### Basic Usage

```bash
# Start interactive mode
ouroboros chat

# Start REST API server (http://localhost:8765)
ouroboros start

# GUI dashboard
# → Open browser to http://localhost:8765 after `ouroboros start`
```

### Python API

```python
from ouroboros import OuroborosMind

# Initialize
mind = OuroborosMind()

# Chat and learn
response = mind.chat("Tell me about reinforcement learning.")
print(response)

# Access raw facts
for fact in mind.crystal.facts:
    print(f"{fact.subject} {fact.relation} {fact.object} [{fact.confidence}]")

# Inspect tensions (curiosity)
for tension in mind.tensions:
    print(f"Tension: {tension.type} — {tension.description}")

# Run a dream pass (self-directed learning)
mind.dream()

# Save and restore
mind.backup("my_memory.backup")
mind.restore("my_memory.backup")
```

### REST API

```bash
# Start server
ouroboros start

# In another terminal:
curl -X POST http://localhost:8765/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "My birthday is May 15th"}'
# → {"response": "Noted. I have crystallized your birthday as May 15th.", "facts_learned": 1}
```

---

## Examples

Seven runnable end-to-end examples in [examples/](examples/):

| # | Example | Purpose |
|---|---------|---------|
| 1 | `01_minimal_chat.py` | Two-turn conversation with crystallized concept inspection |
| 2 | `02_switch_providers.py` | One mind, three LLM providers (seamless switching) |
| 3 | `03_persistence.py` | Save, wipe, restore—facts survive across sessions |
| 4 | `04_privacy_levels.py` | Walk through all 5 privacy bridge levels |
| 5 | `05_http_client.py` | Drive REST API from Python with `httpx` |
| 6 | `06_pipeline_inspection.py` | Inspect each of the 8 chat pipeline steps |
| 7 | `07_dream_and_stats.py` | Run a dream pass and read component stats |

**Run an example:**

```bash
python examples/01_minimal_chat.py
```

---

## Documentation

- **[User Guide](./docs/user_guide.md)** — Installation, configuration, CLI commands, Python API
- **[Architecture](./docs/architecture.md)** — Deep dive into Crystal, Resonance, Tension Engine, Parser, Ranker, Assembler
- **[API Reference](./docs/api_reference.md)** — REST endpoints, WebSocket schema, async patterns
- **[Privacy Model](./docs/privacy.md)** — DigiKabaz integration, PII detection, noise injection
- **[PLAN.md](./PLAN.md)** — Development roadmap, design rationale, future research directions
- **[Benchmark Report](./docs/benchmark_report.md)** — Scalability to 1M facts, latency profiles, storage efficiency

---

## Testing & Development

```bash
# Install dev dependencies
pip install -e .[dev,all]

# Run full test suite (85+ tests)
pytest tests/

# Run with coverage
pytest --cov=src/ouroboros tests/

# Linting & type checking
ruff check .
mypy src/ --strict

# Benchmark scalability (up to 1M facts)
python scripts/bench_scalability_1m.py
```

---

## Performance

**Ingestion:** 29,469 facts/second (constant across all scales)  
**Storage:** 78.5 bytes/fact (1M facts = 74.9 MB)  
**Query Latency:** 0.2ms p50 (O(1) behavior despite 1M facts)  
**Recall Accuracy:** 87–92% (consistent across all scales)  

See [docs/benchmark_report.md](./docs/benchmark_report.md) for detailed results.

---

## Contributing

Ouroboros is community-driven. We welcome:

- **Bug reports** — Use [GitHub Issues](https://github.com/Open-ouroboros/ouroboros-memory/issues)
- **Feature requests** — Include reference to the research paper or design docs
- **Code contributions** — See [CONTRIBUTING.md](CONTRIBUTING.md)
- **Research & papers** — New relation types, tension algorithms, inference strategies

See [DEVELOPMENT.md](DEVELOPMENT.md) for contributor setup and git workflow.

---

## License

Apache License 2.0. See [LICENSE](LICENSE) for details.

**Commercial use is permitted.** No warranty. Use at your own risk.

---

## Citation

If you use Ouroboros Memory in research, please cite:

```bibtex
@software{ouroboros2024,
  title       = {Ouroboros Memory: Symbolic, Contradiction-Aware, Lifelong Memory for LLMs},
  author      = {Open-ouroboros Contributors},
  year        = {2024},
  url         = {https://github.com/Open-ouroboros/ouroboros-memory},
  note        = {v1.0.0, Apache 2.0 License}
}
```

---

## Acknowledgments

Inspired by neuroscience, knowledge representation, and symbolic AI. Built on proven research in:

- **Contradiction detection** — Automated inconsistency resolution in knowledge graphs
- **Curiosity-driven learning** — Tension and novelty as learning drivers
- **Local-first architecture** — Privacy-respecting inference without cloud lock-in
- **Symbolic memory** — Transparent, auditable knowledge storage

---

## Questions?

- **Documentation:** Start with [User Guide](./docs/user_guide.md)
- **Issues:** [GitHub Issues](https://github.com/Open-ouroboros/ouroboros-memory/issues)
- **Discussions:** [GitHub Discussions](https://github.com/Open-ouroboros/ouroboros-memory/discussions)
- **Paper & Theory:** [PLAN.md](./PLAN.md)

**Made with ❤️ by the Ouroboros community.**
