Metadata-Version: 2.4
Name: memory_agent
Version: 2.0.1
Summary: A Python library for advanced memory management in AI agent applications
Author-email: Giuseppe Zileni <giuseppe.zileni@gmail.com>
Project-URL: Homepage, https://gzileni.github.io/memory-agent
Project-URL: Repository, https://github.com/gzileni/memory-agent
Keywords: agent,memory
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE.md
Requires-Dist: aioboto3>=15.1.0
Requires-Dist: aiobotocore>=2.24.0
Requires-Dist: aiofiles>=24.1.0
Requires-Dist: aiohappyeyeballs>=2.6.1
Requires-Dist: aiohttp>=3.11.18
Requires-Dist: aioitertools>=0.12.0
Requires-Dist: aiosignal>=1.3.2
Requires-Dist: annotated-types>=0.7.0
Requires-Dist: anthropic>=0.64.0
Requires-Dist: anyio>=4.9.0
Requires-Dist: attrs>=25.3.0
Requires-Dist: backoff>=2.2.1
Requires-Dist: beautifulsoup4>=4.13.4
Requires-Dist: boto3>=1.39.11
Requires-Dist: botocore>=1.39.11
Requires-Dist: build>=1.2.2.post1
Requires-Dist: certifi>=2025.4.26
Requires-Dist: cffi>=1.17.1
Requires-Dist: chardet>=5.2.0
Requires-Dist: charset-normalizer>=3.4.2
Requires-Dist: click>=8.1.3
Requires-Dist: coloredlogs>=15.0.1
Requires-Dist: contourpy>=1.3.2
Requires-Dist: cryptography>=43.0.0
Requires-Dist: cycler>=0.12.1
Requires-Dist: dataclasses-json>=0.6.7
Requires-Dist: distro>=1.9.0
Requires-Dist: docutils>=0.21.2
Requires-Dist: dydantic>=0.0.8
Requires-Dist: emoji>=2.14.1
Requires-Dist: fastembed>=0.7.0
Requires-Dist: filelock>=3.18.0
Requires-Dist: filetype>=1.2.0
Requires-Dist: flatbuffers>=25.2.10
Requires-Dist: fonttools>=4.58.0
Requires-Dist: fpdf>=1.7.2
Requires-Dist: frozenlist>=1.6.0
Requires-Dist: fsspec>=2024.12.0
Requires-Dist: greenlet>=3.2.2
Requires-Dist: grpcio>=1.74.0
Requires-Dist: h11>=0.16.0
Requires-Dist: h2>=4.2.0
Requires-Dist: hf-xet>=1.1.9
Requires-Dist: hpack>=4.1.0
Requires-Dist: html5lib>=1.1
Requires-Dist: httpcore>=1.0.9
Requires-Dist: httpx>=0.28.1
Requires-Dist: httpx-sse>=0.4.0
Requires-Dist: huggingface-hub>=0.34.4
Requires-Dist: humanfriendly>=10.0
Requires-Dist: hyperframe>=6.1.0
Requires-Dist: id>=1.5.0
Requires-Dist: idna>=3.10
Requires-Dist: iniconfig>=2.1.0
Requires-Dist: jaraco.classes>=3.4.0
Requires-Dist: jaraco.context>=6.0.1
Requires-Dist: jaraco.functools>=4.1.0
Requires-Dist: jiter>=0.9.0
Requires-Dist: jmespath>=1.0.1
Requires-Dist: joblib>=1.5.0
Requires-Dist: json_repair>=0.44.1
Requires-Dist: jsonpatch>=1.33
Requires-Dist: jsonpointer>=2.1
Requires-Dist: keyring>=25.6.0
Requires-Dist: kiwisolver>=1.4.8
Requires-Dist: langchain>=0.3.27
Requires-Dist: langchain-anthropic>=0.3.19
Requires-Dist: langchain-community>=0.3.25
Requires-Dist: langchain-core>=0.3.75
Requires-Dist: langchain-ollama>=0.3.3
Requires-Dist: langchain-openai>=0.3.23
Requires-Dist: langchain-qdrant>=0.2.0
Requires-Dist: langchain-text-splitters>=0.3.10
Requires-Dist: langcodes>=3.5.0
Requires-Dist: langdetect>=1.0.9
Requires-Dist: langgraph>=0.6.6
Requires-Dist: langgraph-checkpoint>=2.1.1
Requires-Dist: langgraph-prebuilt>=0.6.4
Requires-Dist: langgraph-sdk>=0.2.4
Requires-Dist: langmem>=0.0.29
Requires-Dist: langsmith>=0.3.45
Requires-Dist: language_data>=1.3.0
Requires-Dist: loguru>=0.7.3
Requires-Dist: loki-logger-handler>=1.1.2
Requires-Dist: lxml>=5.4.0
Requires-Dist: marisa-trie>=1.3.1
Requires-Dist: Markdown>=3.8.2
Requires-Dist: markdown-it-py>=3.0.0
Requires-Dist: marshmallow>=3.26.1
Requires-Dist: matplotlib>=3.10.3
Requires-Dist: mdurl>=0.1.2
Requires-Dist: mmh3>=5.1.0
Requires-Dist: more-itertools>=10.7.0
Requires-Dist: mpmath>=1.3.0
Requires-Dist: multidict>=6.4.4
Requires-Dist: mypy_extensions>=1.1.0
Requires-Dist: narwhals>=1.43.1
Requires-Dist: neo4j>=5.28.2
Requires-Dist: neo4j-graphrag>=1.9.1
Requires-Dist: nest-asyncio>=1.6.0
Requires-Dist: nh3>=0.2.21
Requires-Dist: nltk>=3.9.1
Requires-Dist: numpy>=2.3.2
Requires-Dist: olefile>=0.47
Requires-Dist: ollama>=0.5.1
Requires-Dist: onnxruntime>=1.22.0
Requires-Dist: openai>=1.86.0
Requires-Dist: orjson>=3.10.18
Requires-Dist: ormsgpack>=1.10.0
Requires-Dist: packaging>=24.2
Requires-Dist: pandas>=2.3.0
Requires-Dist: pillow>=11.2.1
Requires-Dist: plotly>=6.1.2
Requires-Dist: pluggy>=1.6.0
Requires-Dist: portalocker>=2.10.1
Requires-Dist: propcache>=0.3.2
Requires-Dist: protobuf>=4.25.8
Requires-Dist: psutil>=7.0.0
Requires-Dist: py_rust_stemmers>=0.1.5
Requires-Dist: pyaws-s3>=1.0.28
Requires-Dist: pycparser>=2.22
Requires-Dist: pydantic>=2.11.6
Requires-Dist: pydantic-settings>=2.9.1
Requires-Dist: pydantic_core>=2.33.2
Requires-Dist: Pygments>=2.19.1
Requires-Dist: pyparsing>=3.2.3
Requires-Dist: pypdf>=5.6.0
Requires-Dist: pyproject_hooks>=1.2.0
Requires-Dist: pytest>=8.4.1
Requires-Dist: python-dateutil>=2.9.0.post0
Requires-Dist: python-dotenv>=1.1.0
Requires-Dist: python-iso639>=2025.2.18
Requires-Dist: python-magic>=0.4.27
Requires-Dist: python-oxmsg>=0.0.2
Requires-Dist: pytz>=2025.2
Requires-Dist: PyYAML>=6.0.2
Requires-Dist: qdrant-client>=1.14.2
Requires-Dist: RapidFuzz>=3.13.0
Requires-Dist: readme_renderer>=44.0
Requires-Dist: redis>=6.2.0
Requires-Dist: regex>=2024.11.6
Requires-Dist: reportlab>=4.4.2
Requires-Dist: requests>=2.32.4
Requires-Dist: requests-toolbelt>=1.0.0
Requires-Dist: rfc3986>=2.0.0
Requires-Dist: rich>=14.0.0
Requires-Dist: s3transfer>=0.13.1
Requires-Dist: scipy>=1.16.1
Requires-Dist: setuptools>=80.9.0
Requires-Dist: six>=1.17.0
Requires-Dist: sniffio>=1.3.1
Requires-Dist: soupsieve>=2.7
Requires-Dist: SQLAlchemy>=2.0.41
Requires-Dist: sympy>=1.14.0
Requires-Dist: tenacity>=9.1.2
Requires-Dist: tiktoken>=0.9.0
Requires-Dist: tokenizers>=0.21.1
Requires-Dist: tqdm>=4.67.1
Requires-Dist: trustcall>=0.0.39
Requires-Dist: twine>=6.1.0
Requires-Dist: types-PyYAML>=6.0.12.20250516
Requires-Dist: typing-inspect>=0.9.0
Requires-Dist: typing-inspection>=0.4.1
Requires-Dist: typing_extensions>=4.14.0
Requires-Dist: tzdata>=2025.2
Requires-Dist: unstructured>=0.17.2
Requires-Dist: unstructured-client>=0.36.0
Requires-Dist: urllib3>=2.4.0
Requires-Dist: webencodings>=0.5.1
Requires-Dist: wheel>=0.45.1
Requires-Dist: wrapt>=1.17.2
Requires-Dist: xxhash>=3.5.0
Requires-Dist: yarl>=1.20.1
Requires-Dist: zstandard>=0.23.0
Dynamic: license-file

# memory-agent  

[![View on GitHub](https://img.shields.io/badge/View%20on-GitHub-181717?style=for-the-badge&logo=github)](https://github.com/gzileni/memory-agent)  
[![GitHub stars](https://img.shields.io/github/stars/gzileni/memory-agent?style=social)](https://github.com/gzileni/memory-agent/stargazers)  
[![GitHub forks](https://img.shields.io/github/forks/gzileni/memory-agent?style=social)](https://github.com/gzileni/memory-agent/network)  

The library allows you to manage both [persistence](https://langchain-ai.github.io/langgraph/how-tos/persistence/) and [**memory**](https://langchain-ai.github.io/langgraph/concepts/memory/#what-is-memory) for a LangGraph agent.  

**memory-agent** uses [Redis](https://redis.io/) as the short-term memory backend and [QDrant](https://qdrant.tech/) for long-term persistence and semantic search.  

---

## 🔑 Key Features

- **Dual-layer memory system**
  - **Short-term memory with Redis** → ultra-fast, volatile, TTL-based storage for ongoing sessions.
  - **Long-term persistence with Qdrant** → semantic search, embeddings, and retrieval across sessions.
- **LangGraph integration** → build fully stateful LLM-powered agents with checkpoints and memory tools.  
- **Multi-LLM support**
  - [OpenAI](https://platform.openai.com/) (via `AgentOpenAI`)  
  - [Ollama](https://ollama.com/) (via `AgentOllama`) for local inference.  
- **Embeddings flexibility**
  - OpenAI embeddings (default).
  - Hugging Face local embeddings for **air-gapped environments**.
  - Ollama embeddings (`nomic-embed-text`, etc.).  
- **Automatic memory management**
  - Background summarization & reflection to condense context.
  - Checkpoint pruning (`filter_minutes`) for resource control.
- **Observability**
  - Structured logging, **Grafana/Loki compatible**.
- **Easy installation & deployment**
  - Simple `pip install`.
  - Ready-to-use with **Docker** ([docs here](./docker/README.md)).  

---

## Memory vs Persistence  

When developing agents with LangGraph (or LLM-based systems in general), it’s crucial to distinguish between **memory** and **persistence**.  

### Persistence (Qdrant)
- **Permanent storage** across sessions.  
- **Examples:** embeddings, vector databases, long-term conversation history.  
- **Why Qdrant?**
  - Disk persistence.
  - Vector similarity search at scale.
  - Advanced queries with metadata & filters.  

### Memory (Redis)
- **Temporary state** during a conversation or workflow.  
- **Examples:** current conversation state, volatile variables.  
- **Why Redis?**
  - High-performance in-RAM operations.
  - TTL & automatic cleanup.
  - Multi-worker support.  

| Function        | Database | Main Reason                                   |
|-----------------|----------|-----------------------------------------------|
| **Memory**      | Redis    | Performance, TTL, fast session context        |
| **Persistence** | Qdrant   | Vector search, scalable long-term storage     |  

---

## Installation  

```bash
pip install memory-agent
```

For development with Ollama or local embeddings:  

```bash
# Install Ollama
https://ollama.ai  

# Install Hugging Face tools
pip install --upgrade huggingface_hub
```

---

## Usage Examples  

### OpenAI  

```python
import asyncio
from memory_agent.openai import AgentOpenAI
import os

async def main():
    agent = AgentOpenAI(
        key_search="agent_openai_demo",
        model_name="gpt-4.1-mini",
        temperature=0.2,
        model_embedding_name="text-embedding-3-small",
        llm_api_key=os.getenv("OPENAI_API_KEY"),
        thread_id="thread-a"
    )

    result = await agent.ainvoke("Summarize Python 3.12 new features in 3 points.")
    print(result)

    async for chunk in agent.stream("Write a 2-sentence abstract about prompt engineering."):
        print(chunk)

asyncio.run(main())
```

#### Example — Memory per Conversation Thread

```python
import asyncio
from memory_agent.openai import AgentOpenAI
import os

async def main():
    agent = AgentOpenAI(
        key_search="agent_openai_demo",
        model_name="gpt-4.1-mini",
        temperature=0.2,
        model_embedding_name="text-embedding-3-small",
        llm_api_key=os.getenv("OPENAI_API_KEY")
    )

    thread_id: str = "thread-a"

    response = await agent.ainvoke(
        "Know which display mode I prefer?",
        thread_id=thread_id
    )
    print(response["messages"][-1].content)

    # Save a preference in memory
    await agent.ainvoke(
        "dark. Remember that.",
        thread_id=thread_id
    )

    # Continuing in the same thread (thread-a), the agent recalls the preference
    response = await agent.ainvoke(
        "Do you remember my display mode preference?",
        thread_id=thread_id
    )
    print(response["messages"][-1].content)

    thread_id: str = "thread-b"
    response = await agent.ainvoke(
        "Hey there. Do you remember me? What are my preferences?",
        thread_id=thread_id
    )
    print(response["messages"][-1].content)

asyncio.run(main())
```

### Ollama  

```python
import asyncio
from memory_agent.ollama import AgentOllama

async def main():
    agent = AgentOllama(
        key_search="agent_ollama_demo",
        model_name="llama3.1",
        base_url="http://localhost:11434",
        temperature=0.2,
        model_embedding_name="nomic-embed-text",
        model_embedding_url="http://localhost:11434",
        thread_id="thread-a"
    )

    result = await agent.ainvoke("Explain the ReAct pattern in 5 lines.")
    print(result)

    async for chunk in agent.stream("Summarize the last user message in 3 bullet points."):
        print(chunk)

asyncio.run(main())
```

---

## Memory Agents AI  

**MemoryAgent** is also an agent based on LangGraph with long-term memory able to save, search, and synthesize conversation memories.  

- **Types of message storage**
  - `hotpath`: explicit saves performed by the agent via tools (notes or checkpoints created consciously).  
  - `background`: memories automatically extracted from conversations in a “subconscious” way without direct intervention.  

- **Memory management**
  - Obsolete checkpoints can be removed automatically after a configurable interval.  
  - Support for common backends: Redis (storage/checkpointer) and Qdrant (vector indexing and semantic search).  

- **Key features**
  - Orchestration of tools, prompts, and agent logic in synchronous (`ainvoke`) or streaming (`stream`) executions.  
  - Configurable via parameters such as `thread_id`, `key_search`, `host_persistence_config`, `model_name`, etc.  
  - Designed to easily integrate tools and memory/synthesis pipelines from the langmem/langchain ecosystem.  

### Quick best practices
- Keep a stable `thread_id` to grow memory per session/user.  
- Use different `key_search` values for distinct roles or domains.  
- Enable periodic checkpoint cleaning (`refresh_checkpointer=True`) to contain resource usage.  
- Choose Redis for checkpoint persistence and Qdrant for semantic search when vector search is required.  

### Configuration  

Relevant parameters supported by the constructors (via `**kwargs`):  

- `thread_id: str` → Unique conversation ID (default: generated UUID).  
- `key_search: str` → Namespace/key for indexing the agent’s memories.  
- `model_name: str` → Model name (e.g. `gpt-4.1-mini` for OpenAI, `llama3.1` for Ollama).  
- `model_provider: Literal["openai","ollama"]` → Automatically set in wrappers.  
- `base_url: Optional[str]` → Provider endpoint (required for self-hosted instances; default for Ollama: `http://localhost:11434`).  
- `temperature: float` → Model creativity (if supported).  
- `tools: list` → Additional tools to expose to the agent besides memory tools.  
- `max_recursion_limit: int` → Maximum depth of agent steps (approximate default: `25`).  
- `filter_minutes: int` → Time window for checkpoint cleaning (approximate default: `15`).  
- `refresh_checkpointer: bool` → If true, cleans old checkpoints for the current `thread_id`.  
- `host_persistence_config: dict` → Checkpointer backend configuration, e.g.:  
```python
host_persistence_config={
        "host": "localhost",
        "port": 6379,
        "db": 0,
}
```

For OpenAI, ensure you have the ENV:  
```bash
export OPENAI_API_KEY="sk-..."
```

---

## Docker  

See [Docker README](./docker/README.md) for instructions on running Redis, Qdrant, and memory-agent in containers.  

---

## Troubleshooting  

- **Network / 401 error**: verify `OPENAI_API_KEY` (for OpenAI) or the reachability of `base_url` (for Ollama).  
- **Model not found**: in Ollama run `ollama pull llama3.1` (or the model you want).  
- **Token limit exceeded**: reduce `max_recursion_limit`, use lower temperature, or enable/refine short-term synthesis.  
- **Store/Checkpointer**: if using Redis or another backend, verify `host_persistence_config`.  

---

Semantic Memory: https://langchain-ai.github.io/langmem/guides/extract_semantic_memories/#when-to-use-semantic-memories
