Metadata-Version: 2.4
Name: intentmind
Version: 0.4.0
Summary: Language-agnostic associative memory runtime for persistent AI systems
Author: Intentmind Contributors
License: Intentmind Fair-Code License (Non-Commercial)
Project-URL: Homepage, https://github.com/avnialkan/intentmind
Project-URL: Repository, https://github.com/avnialkan/intentmind
Project-URL: Issues, https://github.com/avnialkan/intentmind/issues
Keywords: ai,memory,agents,rag,graph,retrieval,embeddings
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Provides-Extra: faiss
Requires-Dist: faiss-cpu>=1.7.0; extra == "faiss"
Requires-Dist: numpy>=1.24; extra == "faiss"
Provides-Extra: sentence-transformers
Requires-Dist: sentence-transformers>=2.7.0; extra == "sentence-transformers"
Provides-Extra: vis
Requires-Dist: networkx>=3.0; extra == "vis"
Requires-Dist: pyvis>=0.3.2; extra == "vis"
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.1.0; extra == "langchain"
Provides-Extra: llm
Requires-Dist: openai>=1.0.0; extra == "llm"
Requires-Dist: python-dotenv>=1.0.0; extra == "llm"
Provides-Extra: api
Requires-Dist: fastapi>=0.110.0; extra == "api"
Requires-Dist: uvicorn[standard]>=0.29.0; extra == "api"
Requires-Dist: openai>=1.0.0; extra == "api"
Requires-Dist: python-dotenv>=1.0.0; extra == "api"
Requires-Dist: sentence-transformers>=2.7.0; extra == "api"
Requires-Dist: faiss-cpu>=1.7.0; extra == "api"
Requires-Dist: numpy>=1.24; extra == "api"
Provides-Extra: benchmark
Requires-Dist: tqdm>=4.66.0; extra == "benchmark"
Requires-Dist: openai>=1.0.0; extra == "benchmark"
Requires-Dist: python-dotenv>=1.0.0; extra == "benchmark"
Provides-Extra: all
Requires-Dist: sentence-transformers>=2.7.0; extra == "all"
Requires-Dist: networkx>=3.0; extra == "all"
Requires-Dist: pyvis>=0.3.2; extra == "all"
Requires-Dist: langchain-core>=0.1.0; extra == "all"
Requires-Dist: faiss-cpu>=1.7.0; extra == "all"
Requires-Dist: numpy>=1.24; extra == "all"
Requires-Dist: openai>=1.0.0; extra == "all"
Requires-Dist: python-dotenv>=1.0.0; extra == "all"
Dynamic: license-file

# Intentmind 🧠

![PyPI version](https://img.shields.io/pypi/v/intentmind)
![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)
![License](https://img.shields.io/badge/license-Fair--Code-orange)

**Intentmind** is a **Cognitive Operating Layer for Persistent AI**. It acts as the foundational "Memory OS" for autonomous AI agents, copilots, simulators, and AI NPCs.

It moves beyond standard RAG by mimicking human cognitive processes—building a dynamic **Knowledge Graph**, forming associative connections, and employing biological "forgetting" mechanisms to maintain a pristine, highly relevant context window over months or years of interactions.

---

## 🛑 The Problem with Classic RAG

If you are building an autonomous system or an AI agent that lives for more than a single session, you will quickly hit the limits of standard Vector Database RAG wrappers:

1. **Amnesia by Proxy:** Standard RAG relies on overlapping embeddings. If a user talks about buying a *"car"* on Monday, and asks for help with *"insurance"* on Friday, standard RAG will fail to connect them unless the exact keywords or vector spaces strictly align.
2. **Context Bloat:** Vector DBs append data forever. Over time, your agent gets overwhelmed by thousands of trivial, outdated, or conflicting memories, destroying the LLM's accuracy.
3. **Flat Representation:** Standard RAG treats all data equally. It lacks the ability to understand that some memories are core to the user's identity, while others were just passing thoughts.

## 🌟 The Solution: Why Intentmind?

Intentmind doesn't just store documents; it builds a **dynamic associative memory graph with energy-based activation, decay, reinforcement, and traceable recall paths**. It acts as a living, breathing cognitive architecture.

### 1. Associative Recall (Semantic Drift Recovery)
When data is ingested, Intentmind extracts core concepts (nodes) and connects them (edges). When a user mentions a concept, the system doesn't just do a vector search—it **traverses the graph**. 

**Example of Semantic Drift:**
User talks about their *car* ➔ then plans a *trip* ➔ then asks about *insurance*. 
Intentmind naturally traverses the graph from `car` to `insurance`, pulling in the exact historical context your agent needs to sound truly intelligent, even if the raw embeddings don't directly match.

### 2. Biological Forgetting (Energy & Decay)
Intentmind introduces an `Energy` system. Every time a memory is recalled, its connection strengthens (like human synapses). Unused, irrelevant, or noisy memories slowly decay and are eventually "forgotten" (archived). This prevents context bloat and ensures your agent only remembers what actually matters.

### 3. Language-Agnostic Root Intelligence (Lemmatization)
To prevent "Intent Explosion" (e.g. `car`, `cars`, `my car` all becoming separate nodes), Intentmind uses a proprietary **Language-Agnostic Soft-Match Algorithm**. It combines High Vector Similarity (>82%) with Lexical Overlap (Prefix-matching >60%) to organically merge inflections and typos into aliases of a single root intent, without needing language-specific NLP libraries (like NLTK or Zemberek).

### 4. Dynamic Edge Confidence (State Machine)
Graphs easily turn into useless spaghetti if edges are formed too quickly. Intentmind features a rigorous **Edge State Machine** (`Candidate` -> `Weak` -> `Active`). Edges are evaluated based on Co-occurrence Frequency, Semantic Consistency, Temporal Recurrence, and Domain Alignment. A passing mention creates a mere "Candidate" edge which doesn't pollute recall until it is corroborated!

### 5. Semantic Consolidation & Contradiction Engine
Intentmind's background `tick()` lifecycle actively monitors the `episodic` memory pool. As patterns emerge (e.g. "User drank espresso", "User hates filter coffee"), the **Consolidation Engine** automatically uses an LLM to synthesize **Semantic Facts** ("User likes espresso, dislikes filter coffee") while archiving the raw events. If a user later says "I actually love filter coffee now," the **Contradiction Engine** catches the conflict, decays the old semantic fact, and solidifies the new truth.

### 6. Cognitive State Modulation
Previously known as the "Emotion Engine", this system features an **Adaptive Urgency Matrix**. It dynamically scores the user's current query for stress, urgency, or sentiment, and applies **retrieval priority modulation**. A highly urgent query immediately surfaces hard, high-confidence facts, while a casual conversational query triggers broader, associative exploration.

---

## ⚔️ Why not just GraphRAG?

GraphRAG is fantastic for static document analysis, but it fails for **persistent, living agents**. 

| Feature | Vanilla RAG | GraphRAG | Intentmind |
| :--- | :--- | :--- | :--- |
| **Primary Use Case** | Q&A on Docs | Knowledge Discovery | **Living AI Agents** |
| **Memory Architecture** | Static Vectors | Static Graph | **Dynamic Fluid Graph** |
| **Associative Activation** | No | Hardcoded Edges | **Energy Propagation** |
| **Memory Aging** | No (Bloats forever) | No | **Biological Forgetting (Decay)** |
| **Reinforcement** | No | No | **Synaptic Strengthening via Reuse** |

## 📊 Performance Benchmarks

*Synthetic Semantic Drift Benchmark*
- **Dataset:** 1,000 memory facts
- **Noise:** 30%
- **Query type:** delayed indirect recall

| System | Accuracy |
| :--- | :--- |
| Vanilla vector search | 42% |
| **Intentmind** | **68%** |

*Note: These are local regression benchmarks, not independent research claims. Intentmind is built to be resilient to long-session degradation where other systems degrade.*

---

## 🎯 Who is this for?

- **Autonomous Agents & AI Personas:** Give your AI agents long-term, evolving memory. As they interact with the world, their internal cognitive graph adapts, making them highly personalized and context-aware.
- **Persistent Copilots:** Build customer support bots, coding assistants, or personal companions that remember user preferences seamlessly over years of interaction without polluting the LLM context window.
- **Complex Simulators:** Drive simulations where multiple entities negotiate, learn, and forget based on cognitive connections.

---

## 🚀 Quick Start

### Installation

```bash
# Core package
pip install intentmind

# With recommended production dependencies (FAISS, SentenceTransformers, OpenAI)
pip install "intentmind[all]"
```

### 1-Minute Integration

While the core graph logic is language-agnostic, extraction quality is **embedding-model dependent**. We recommend using multilingual models for non-English data.

```python
from intentmind import IntentmindMemory
from intentmind.embeddings import SentenceTransformerEmbedder

# Option A: Local deterministic demo (fastest, no LLM needed)
mem = IntentmindMemory(is_test=True, core_extractor="deterministic")

# Option B: Production embeddings with deterministic extraction
# mem = IntentmindMemory(embedder=SentenceTransformerEmbedder(), core_extractor="deterministic")

# Option C: Production with full LLM-assisted extraction (requires OPENAI_API_KEY)
# mem = IntentmindMemory(embedder=SentenceTransformerEmbedder(), core_extractor="llm")

# 2. Teach it concepts (Happens naturally during conversation)
mem.add("I need car insurance but I have no money.")
mem.add("I bought a new car and will drive to London.")

# 3. Ask a tangential question
result = mem.query("I have a car and I am going to London.")

# 4. Watch it traverse the graph and retrieve the exact context
for item in result["memories"]["items"]:
    print(f"[{item['layer']}] Path: {item.get('path', [])} -> {item['text']}")
```

---

## 🔌 Seamless Integrations

### LangChain Adapter
Drop Intentmind straight into your existing LangChain pipelines as a custom, ultra-smart Retriever.
```python
from intentmind.integrations.langchain import IntentmindRetriever

retriever = IntentmindRetriever(memory=mem)
docs = retriever.invoke("How does the energy model work?")
```

### Persistence (Save & Load)
Save the entire brain (vectors, nodes, edges, decay states) to disk instantly.
```python
mem.save("my_agent_brain.json")
mem = IntentmindMemory.load("my_agent_brain.json")
```

---

## 📊 Visualizing the "Brain"

Intentmind isn't a black box. You can export the entire Cognitive Graph to an interactive HTML map to visualize the graph structure, energy levels, and synaptic connections.

```python
mem.visualize("memory_map.html")
```
*(Open `memory_map.html` in your browser to explore clustering, energy levels, and synaptic connections)*

---

## 🌐 Demo API & React UI

Intentmind includes a built-in FastAPI backend and a beautiful React/Vite UI to test your graphs visually.

1. **Start Backend:**
   ```bash
   pip install "intentmind[api]"
   # Make sure OPENAI_API_KEY is in your .env
   python api.py
   ```
2. **Start Frontend UI:**
   ```bash
   cd ui
   npm install
   npm run dev
   ```

---

## 🤝 Contributing & License

Intentmind is released under the **Intentmind Fair-Code License**. 

- **Personal & Academic Use:** Completely free! You can use, modify, and experiment with Intentmind for your personal projects, academic research, or hobby apps.
- **Commercial Use:** If you plan to use Intentmind in a commercial product, SaaS, or any revenue-generating service, you **must** obtain prior written consent or a commercial license. 

For commercial licensing inquiries, please reach out via GitHub issues or contact the author directly.

We welcome contributions for new embedders, LLM adapters, and vector store integrations! Build the future of AI memory with us.
