Metadata-Version: 2.4
Name: myelinmod
Version: 0.1.1
Summary: Universal Cognitive Memory Adapter — persistent memory, adaptive continuity, and lifelong learning for autonomous AI systems
Project-URL: Homepage, https://github.com/jalaluddinkhan1/Myelin
Project-URL: Documentation, https://github.com/jalaluddinkhan1/Myelin#readme
Project-URL: Repository, https://github.com/jalaluddinkhan1/Myelin
Project-URL: Bug Tracker, https://github.com/jalaluddinkhan1/Myelin/issues
Project-URL: Changelog, https://github.com/jalaluddinkhan1/Myelin/blob/main/CHANGELOG.md
Author: Myelin Authors
License: MIT License
        
        Copyright (c) 2025 Myelin Authors
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: agent,ai,anthropic,autonomous-agents,cognitive,episodic-memory,langchain,llm,memory,openai,persistent-memory,rag,semantic-memory
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: alembic>=1.13.0
Requires-Dist: anthropic>=0.30.0
Requires-Dist: anyio>=4.4.0
Requires-Dist: apscheduler>=3.10.0
Requires-Dist: asyncpg>=0.29.0
Requires-Dist: cachetools>=5.4.0
Requires-Dist: cryptography>=42.0.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: msgpack>=1.0.8
Requires-Dist: neo4j>=5.21.0
Requires-Dist: numpy>=1.26.0
Requires-Dist: openai>=1.35.0
Requires-Dist: opentelemetry-api>=1.25.0
Requires-Dist: opentelemetry-sdk>=1.25.0
Requires-Dist: orjson>=3.10.0
Requires-Dist: pydantic-settings<3,>=2.3.0
Requires-Dist: pydantic<3,>=2.7.0
Requires-Dist: qdrant-client>=1.9.0
Requires-Dist: redis[asyncio]>=5.0.0
Requires-Dist: sentence-transformers>=3.0.0
Requires-Dist: sqlalchemy[asyncio]<3,>=2.0.30
Requires-Dist: structlog>=24.2.0
Requires-Dist: tenacity>=8.3.0
Provides-Extra: all
Requires-Dist: fastapi>=0.111.0; extra == 'all'
Requires-Dist: langchain-core>=0.2.0; extra == 'all'
Requires-Dist: opentelemetry-exporter-otlp>=1.25.0; extra == 'all'
Requires-Dist: uvicorn[standard]>=0.30.0; extra == 'all'
Provides-Extra: dev
Requires-Dist: faker>=25.0.0; extra == 'dev'
Requires-Dist: mypy>=1.10.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
Requires-Dist: pytest>=8.2.0; extra == 'dev'
Requires-Dist: ruff>=0.4.0; extra == 'dev'
Requires-Dist: types-cachetools>=5.3.0; extra == 'dev'
Requires-Dist: types-redis>=4.6.0; extra == 'dev'
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.2.0; extra == 'langchain'
Provides-Extra: proxy
Requires-Dist: fastapi>=0.111.0; extra == 'proxy'
Requires-Dist: uvicorn[standard]>=0.30.0; extra == 'proxy'
Provides-Extra: telemetry
Requires-Dist: opentelemetry-exporter-otlp>=1.25.0; extra == 'telemetry'
Description-Content-Type: text/markdown

# Myelin

**Universal Cognitive Memory Adapter for Autonomous AI Systems**

[![PyPI](https://img.shields.io/pypi/v/myelinmod)](https://pypi.org/project/myelinmod/)
[![Python](https://img.shields.io/pypi/pyversions/myelinmod)](https://pypi.org/project/myelinmod/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![CI](https://github.com/jalaluddinkhan1/Myelin/actions/workflows/ci.yml/badge.svg)](https://github.com/jalaluddinkhan1/Myelin/actions/workflows/ci.yml)
[![Coverage](https://img.shields.io/codecov/c/github/jalaluddinkhan1/Myelin)](https://codecov.io/gh/jalaluddinkhan1/Myelin)

---

## What is Myelin?

Every AI model today — GPT-4, Claude, Llama, anything — forgets everything the moment a conversation ends. Myelin fixes that.

Myelin is a **drop-in cognitive memory layer** that wraps any LLM and gives it:

- **Persistent long-term memory** across sessions, users, and time
- **9 distinct memory types** modelled on human cognition
- **Adaptive learning** — the system gets smarter from every interaction
- **Intelligent forgetting** — Ebbinghaus decay, not deletion
- **Cross-agent shared cognition** — multiple agents sharing the same memory fabric
- **Full cognitive pipeline** — reflection, dreaming, evolution, compression — running automatically in the background

In the same way RAG became the retrieval layer for modern AI, Myelin is the **persistence and continuity layer** for next-generation autonomous AI.

---

## Install

```bash
pip install myelinmod
```

Requires Python 3.11+ and a running instance of the backend stack (see [Infrastructure](#infrastructure)).

---

## Prerequisites

Before running any example, start the backend services and set your API keys:

```bash
# 1. Start backend (Qdrant, Neo4j, PostgreSQL, Redis)
docker compose up -d

# 2. Run migrations
alembic upgrade head
```

```python
import os

# Set your API keys (or put these in a .env file — never commit secrets)
os.environ["OPENAI_API_KEY"] = "sk-..."        # for OpenAI examples
os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..." # for Anthropic examples
```

---

## 60-Second Quick Start

> **Jupyter / IPython:** use `await main()` directly — an event loop is already running.
> **Python script:** use `asyncio.run(main())` instead.

```python
import os
import asyncio
from myelin import CognitiveAdapter, MyelinConfig

os.environ["OPENAI_API_KEY"] = "sk-..."  # or load from .env

async def main():
    config = MyelinConfig(agent_id="my-agent")

    async with CognitiveAdapter.session(config) as agent:
        client = agent.openai_client  # drop-in for openai.AsyncOpenAI

        response = await client.chat.completions.create(
            model="gpt-4o",
            messages=[{"role": "user", "content": "What did we work on last week?"}],
        )
        print(response.choices[0].message.content)
        # The model now has memory of every past interaction.

# In a Jupyter notebook:
await main()

# In a Python script, replace the line above with:
# asyncio.run(main())
```

That's it. **Zero code changes** to your existing LLM calls. Myelin intercepts, enriches with memory, and learns from every response automatically.

---

## Drop-in Adapters

### Step 1 — Connect the fabric (run this cell once; reuse `fabric` in every example below)

```python
import os
from myelin import HybridMemoryFabric, MyelinConfig

os.environ["OPENAI_API_KEY"] = "sk-..."
os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."

config = MyelinConfig(agent_id="agent-1")
fabric = HybridMemoryFabric.from_config(config)
await fabric.connect()
print("fabric connected")
```

### OpenAI

```python
# Before (plain openai — no memory):
# from openai import AsyncOpenAI
# client = AsyncOpenAI(api_key=os.environ["OPENAI_API_KEY"])

# After — identical API, full cognitive memory:
from myelin import MyelinOpenAI

client = MyelinOpenAI(fabric=fabric, agent_id="agent-1")

response = await client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello"}],
)
print(response.choices[0].message.content)
```

### Anthropic

```python
# Requires: fabric connected (Step 1 above)
from myelin import MyelinAnthropic

client = MyelinAnthropic(fabric=fabric, agent_id="agent-1")

response = await client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello"}],
)
print(response.content[0].text)
```

### Streaming

```python
# Requires: client created (OpenAI or Anthropic step above)
# Memory is logged automatically after the stream completes
async for text_chunk in await client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True,
):
    print(text_chunk, end="", flush=True)
```

### LangChain

```python
# Requires: fabric connected (Step 1 above) and llm defined
from myelin.integrations.langchain import MyelinChatMemory
from langchain.chains import ConversationChain

memory = MyelinChatMemory(agent_id="agent-1", session_id="session-abc")
memory.bind_fabric(fabric)

chain = ConversationChain(llm=llm, memory=memory)
```

### Local / Open-Source Models (Ollama, vLLM, LM Studio)

```python
# Any OpenAI-compatible endpoint — requires: fabric connected (Step 1 above)
from myelin import MyelinOpenAI

client = MyelinOpenAI(
    fabric=fabric,
    agent_id="agent-1",
    openai_base_url="http://localhost:11434/v1",  # Ollama
    openai_api_key="ollama",
)
```

---

## The 9 Memory Types

| Type | Backend | What it stores |
|---|---|---|
| **Episodic** | Qdrant (vector) | Every interaction — time, context, outcome |
| **Semantic** | Neo4j (graph) | Concepts, facts, relationships |
| **Procedural** | PostgreSQL | Skills, how-to sequences, success rates |
| **Causal** | Neo4j (DAG) | Cause-effect chains, counterfactuals |
| **Reflective** | PostgreSQL | Self-model, capabilities, known biases |
| **Predictive** | PostgreSQL | Forecasts, simulations, expected outcomes |
| **Short-Term** | Redis (TTL) | Active session context, expires automatically |
| **Preference** | PostgreSQL | User preferences, emotional weights, affinities |
| **Meta** | PostgreSQL | Confidence in its own knowledge, known gaps |

---

## Cognitive Pipeline

Every call triggers this pipeline automatically:

```
User message
    ↓
[Myelin intercepts]
    ↓
Search all 9 memory stores simultaneously
    ↓
Score + rank via Memory Router (8-component relevance function)
    ↓
Inject top memories into system prompt
    ↓
Call LLM → return response to user
    ↓  (background — never blocks the user)
Write episodic memory
    ↓
Reflection (failure analysis, self-model update)
    ↓
Evolution (router weight update from retrieval quality)
    ↓
Dreaming (nightly: replay, compress, extract patterns)
```

---

## Writing and Querying Memory Directly

```python
# Requires: fabric connected (Step 1 in Drop-in Adapters above)
from myelin import EpisodicMemory, CQLQuery, EpisodeOutcome, OutcomeLabel

# Write any memory type directly
episode = EpisodicMemory(
    agent_id="agent-1",
    content="Deployed the new auth service. All tests passed.",
    outcome=EpisodeOutcome(label=OutcomeLabel.SUCCESS),
    tags=["deployment", "auth"],
)
memory_id = await fabric.write(episode)

# Query across all memory types
results = await fabric.query(CQLQuery(
    query_text="auth deployment",
    agent_id="agent-1",
    limit=10,
))

for r in results:
    print(f"[{r.memory.memory_type}] score={r.score.total_score:.2f}: {r.memory}")

# Convenience methods
episodes = await fabric.query_episodic("agent-1", "deployment", limit=5)
concepts = await fabric.query_semantic("agent-1", "authentication")
skill    = await fabric.find_skill("deploy_service", "agent-1")
prefs    = await fabric.get_preferences("agent-1", subject="code style")
gaps     = await fabric.get_known_gaps("agent-1")
```

---

## Cross-Agent Memory Sharing

```python
from myelin import MemorySyncLayer, SyncScope

# Agent A publishes a memory
sync_a = MemorySyncLayer("agent-a", namespace="my-team", scope=SyncScope.TEAM)
await sync_a.connect("redis://localhost:6379")
await sync_a.publish(episode)

# Agent B receives it automatically
sync_b = MemorySyncLayer("agent-b", namespace="my-team")
await sync_b.connect("redis://localhost:6379")
sync_b.on_receive(lambda event: print(f"Received from {event.source_agent_id}"))
```

---

## Identity Core

```python
from myelin import IdentityCore

# Create a cryptographically signed agent identity
identity, private_key_pem = IdentityCore.create(
    agent_id="agent-1",
    name="Research Assistant",
    core_values=["accuracy", "helpfulness", "honesty"],
    behavioral_constraints=["never fabricate citations"],
    primary_goal="Answer research questions accurately",
)
identity.save("agent_identity.json", private_key_pem)

# Load and verify on restart — raises ValueError if tampered
identity = IdentityCore.load("agent_identity.json")
```

---

## Infrastructure

Myelin requires these backend services. Start them with the included Docker Compose:

```bash
docker compose up -d
```

| Service | Purpose | Default port |
|---|---|---|
| Qdrant | Episodic + predictive vector search | 6333 |
| Neo4j | Semantic + causal graph | 7687 |
| TimescaleDB (PostgreSQL) | Procedural, reflective, preference, meta | 5432 |
| Redis | Short-term memory + cross-agent sync | 6379 |

**Run database migrations:**
```bash
alembic upgrade head
```

---

## Configuration

All configuration via environment variables or `.env` file:

```env
MYELIN_AGENT_ID=my-agent
MYELIN_QDRANT_URL=http://localhost:6333
MYELIN_NEO4J_URI=bolt://localhost:7687
MYELIN_NEO4J_USER=neo4j
MYELIN_NEO4J_PASSWORD=password
MYELIN_POSTGRES_DSN=postgresql+asyncpg://myelin:myelin@localhost:5432/myelin
MYELIN_REDIS_URL=redis://localhost:6379
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
```

---

## OpenTelemetry

```python
from myelin.telemetry.tracing import configure_tracing

configure_tracing(
    service_name="my-ai-service",
    service_version="1.0.0",
    # auto-reads OTEL_EXPORTER_OTLP_ENDPOINT from env
)
```

Spans are emitted for: `fabric.write`, `fabric.query`, `adapter.openai.create`, `adapter.anthropic.create`, `module.dreaming`, `module.reflection`.

---

## Cognitive Health

```python
import os
from myelin import CognitiveAdapter, MyelinConfig

os.environ["OPENAI_API_KEY"] = "sk-..."

config = MyelinConfig(agent_id="my-agent")

async with CognitiveAdapter.session(config) as agent:
    health = await agent.cognitive_health()
    # {
    #   "stores": {"episodic": true, "semantic": true, ...},
    #   "budget_utilization": {"memory": 0.23, "context_tokens": 0.41},
    #   "warnings": [],
    # }

    # Manual triggers
    await agent.trigger_dreaming()
    await agent.trigger_compression()
```

---

## Supported Python Versions

| Python | Support |
|--------|---------|
| 3.11 | ✅ Fully supported |
| 3.12 | ✅ Fully supported |
| 3.10 | ❌ Not supported (StrEnum, match) |

---

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md). Issues and PRs welcome.

## Security

See [SECURITY.md](SECURITY.md) for reporting vulnerabilities.

## License

[MIT](LICENSE) — free for commercial and open-source use.
