Metadata-Version: 2.4
Name: neural-ai-memory
Version: 0.2.0
Summary: A brain-inspired, dynamic memory system for AI applications
Project-URL: Homepage, https://github.com/Reezxy/Neural-AI-Memory-system
Project-URL: Repository, https://github.com/Reezxy/Neural-AI-Memory-system
Project-URL: Issues, https://github.com/Reezxy/Neural-AI-Memory-system/issues
License: MIT License
        
        Copyright (c) 2026 Reezxy
        
        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: ai,knowledge-graph,llm,memory,vector-database
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
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: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Requires-Dist: chromadb>=0.4.0
Requires-Dist: networkx>=3.0
Requires-Dist: numpy>=1.24.0
Requires-Dist: pydantic>=2.0
Provides-Extra: all
Requires-Dist: anthropic>=0.20; extra == 'all'
Requires-Dist: openai>=1.0; extra == 'all'
Requires-Dist: sentence-transformers>=2.2; extra == 'all'
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.20; extra == 'anthropic'
Provides-Extra: dev
Requires-Dist: black>=23.0; extra == 'dev'
Requires-Dist: mypy>=1.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff>=0.1; extra == 'dev'
Provides-Extra: local
Requires-Dist: sentence-transformers>=2.2; extra == 'local'
Provides-Extra: openai
Requires-Dist: openai>=1.0; extra == 'openai'
Description-Content-Type: text/markdown

# neural-memory

A brain-inspired, dynamic memory layer for AI applications.

Most AI systems treat memory as a static store — embed text, retrieve by similarity. `neural-memory` goes further: memories have **importance scores**, **decay over time**, get **reinforced on access**, and can be automatically **merged** or **abstracted** into higher-level concepts.

```python
from neural_memory import MemorySystem
from neural_memory.providers import LocalProvider

mem = MemorySystem(provider=LocalProvider())

mem.store("The user prefers concise responses.")
mem.store("Project deadline is 2026-05-01", importance=0.9)

results = mem.recall("How should I respond to the user?")
print(results[0].memory.content)
# → "The user prefers concise responses."
```

---

## Installation

**No API key required (local embeddings):**
```bash
pip install neural-ai-memory[local]
```

**With OpenAI:**
```bash
pip install neural-ai-memory[openai]
```

**With Anthropic (Claude):**
```bash
pip install neural-ai-memory[anthropic,local]
```

---

## Providers

| Provider | Embeddings | LLM scoring | Requires |
|---|---|---|---|
| `LocalProvider` | sentence-transformers | heuristic | `neural-memory[local]` |
| `OpenAIProvider` | text-embedding-3-small | gpt-4o-mini | `neural-memory[openai]` |
| `AnthropicProvider` | sentence-transformers | Claude Haiku | `neural-memory[anthropic,local]` |

```python
from neural_memory.providers import OpenAIProvider, AnthropicProvider

# OpenAI
mem = MemorySystem(provider=OpenAIProvider(api_key="sk-..."))

# Anthropic
mem = MemorySystem(provider=AnthropicProvider(api_key="sk-ant-..."))

# Custom: subclass BaseLLMProvider and implement embed(), score_importance(), complete()
```

---

## API

### `store(content, importance=None, context=None, tags=None, metadata=None) → Memory`

Ingest and persist a piece of information. Importance is scored automatically unless overridden.

```python
mem.store("Alice is the project lead", tags=["team"])
mem.store("Deploy by Friday", importance=0.95, metadata={"source": "slack"})
```

### `store_many(contents, importance=None, ...) → List[Memory]`

Batch ingest — embeddings computed in **one call** instead of N. Significantly faster for large imports.

```python
facts = ["Fact one", "Fact two", "Fact three"]
memories = mem.store_many(facts, importance=0.7)
```

### `recall(query, top_k=5, context=None, min_importance=0.0) → List[RetrievalResult]`

Retrieve the most relevant memories. Scoring combines semantic relevance, importance, and recency.

```python
results = mem.recall("Who is responsible for deployment?", top_k=3)
for r in results:
    print(f"{r.final_score:.2f}  {r.memory.content}")
```

### `forget(memory_id)`

Permanently delete a memory.

```python
mem.forget(memory.id)
```

### `run_maintenance() → dict`

Trigger lifecycle operations manually (also runs automatically every 50 stores):

- **Decay** — importance drops for memories not accessed recently
- **Prune** — memories below threshold are deleted
- **Merge** — highly similar memories are combined into one
- **Abstract** — clusters of related memories become a single concept

```python
summary = mem.run_maintenance()
# → {"decayed": 12, "pruned": 3, "merged": 2, "abstracted": 1}
```

### `stats() → MemoryStats`

```python
s = mem.stats()
print(s.total_memories, s.avg_importance, s.by_category)
```

---

## Configuration

```python
from neural_memory import MemorySystem, MemoryConfig, LifecycleConfig, RetrievalWeights

config = MemoryConfig(
    persist_directory="./my_memory",
    retrieval=RetrievalWeights(relevance=0.5, importance=0.3, recency=0.2),
    lifecycle=LifecycleConfig(
        decay_rate=0.05,           # importance lost per day of inactivity
        decay_threshold=0.05,      # memories below this are pruned
        merge_similarity_threshold=0.92,
        abstraction_cluster_size=5,
        auto_maintenance_interval=50,
    ),
    use_llm_importance_scoring=True,
    recency_half_life_days=7.0,
)

mem = MemorySystem(provider=LocalProvider(), config=config)
```

---

## Architecture

```
store(text)
    │
    ▼
IngestionLayer          normalize, tag detection, metadata
    │
    ▼
EncodingLayer           embed, importance score, category classification
    │
    ├──▶ VectorStorage  ChromaDB — semantic search
    ├──▶ KVStorage      dict/JSON — fast ID lookup
    └──▶ GraphStorage   networkx — relationship tracking

recall(query)
    │
    ▼
RetrievalEngine         weighted score: relevance × 0.5 + importance × 0.3 + recency × 0.2
    │
    ▼
LifecycleManager        reinforce accessed memories

run_maintenance()
    │
    ├── decay + prune
    ├── merge similar pairs
    └── abstract clusters → concept memories
```

---

## Async API

Every method has an async equivalent — safe to use in FastAPI, asyncio, or any async framework:

```python
from neural_memory import MemorySystem
from neural_memory.providers import LocalProvider

mem = MemorySystem(provider=LocalProvider())

# In an async function:
m = await mem.astore("Deadline is Friday", importance=0.9)
results = await mem.arecall("When is the deadline?")
await mem.aforget(m.id)
summary = await mem.arun_maintenance()

# Batch async:
memories = await mem.astore_many(["Fact A", "Fact B", "Fact C"])
```

Auto-maintenance triggered by `store()` always runs in a **background thread** — it never blocks the calling code.

---

## Extending

Implement `BaseLLMProvider` to add any embedding or LLM backend:

```python
from neural_memory import BaseLLMProvider, MemorySystem

class MyProvider(BaseLLMProvider):
    def embed(self, text: str) -> list[float]:
        ...

    def score_importance(self, content: str, context=None) -> float:
        ...

    def complete(self, prompt: str) -> str:
        ...

mem = MemorySystem(provider=MyProvider())
```

---

## License

MIT
