Metadata-Version: 2.1
Name: memoripy
Version: 0.1.0
Summary: Memoripy provides context-aware memory management with support for OpenAI and Ollama APIs, offering structured short-term and long-term memory storage for interactive applications.
Home-page: https://github.com/caspianmoon/memoripy
Author: Khazar Ayaz
Author-email: khazar.ayaz@personnoai.com
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: aiohappyeyeballs==2.4.3
Requires-Dist: aiohttp==3.10.10
Requires-Dist: aiosignal==1.3.1
Requires-Dist: annotated-types==0.7.0
Requires-Dist: anyio==4.6.2.post1
Requires-Dist: attrs==24.2.0
Requires-Dist: certifi==2024.8.30
Requires-Dist: charset-normalizer==3.4.0
Requires-Dist: distro==1.9.0
Requires-Dist: faiss-cpu==1.8.0.post1
Requires-Dist: frozenlist==1.5.0
Requires-Dist: h11==0.14.0
Requires-Dist: httpcore==1.0.6
Requires-Dist: httpx==0.27.2
Requires-Dist: idna==3.10
Requires-Dist: jiter==0.7.0
Requires-Dist: joblib==1.4.2
Requires-Dist: jsonpatch==1.33
Requires-Dist: jsonpointer==3.0.0
Requires-Dist: langchain==0.3.7
Requires-Dist: langchain-core==0.3.15
Requires-Dist: langchain-ollama==0.2.0
Requires-Dist: langchain-openai==0.2.5
Requires-Dist: langchain-text-splitters==0.3.2
Requires-Dist: langsmith==0.1.139
Requires-Dist: multidict==6.1.0
Requires-Dist: networkx==3.4.2
Requires-Dist: numpy==1.26.4
Requires-Dist: ollama==0.3.3
Requires-Dist: openai==1.53.0
Requires-Dist: orjson==3.10.11
Requires-Dist: packaging==24.1
Requires-Dist: propcache==0.2.0
Requires-Dist: pydantic==2.9.2
Requires-Dist: pydantic_core==2.23.4
Requires-Dist: PyYAML==6.0.2
Requires-Dist: regex==2024.9.11
Requires-Dist: requests==2.32.3
Requires-Dist: requests-toolbelt==1.0.0
Requires-Dist: scikit-learn==1.5.2
Requires-Dist: scipy==1.14.1
Requires-Dist: setuptools==75.3.0
Requires-Dist: sniffio==1.3.1
Requires-Dist: SQLAlchemy==2.0.36
Requires-Dist: tenacity==9.0.0
Requires-Dist: threadpoolctl==3.5.0
Requires-Dist: tiktoken==0.8.0
Requires-Dist: tqdm==4.66.6
Requires-Dist: typing_extensions==4.12.2
Requires-Dist: urllib3==2.2.3
Requires-Dist: yarl==1.17.1

# Memoripy

**Memoripy** is a Python library designed to manage and retrieve context-aware memory interactions using both short-term and long-term storage. It supports AI-driven applications requiring memory management, with compatibility for OpenAI and Ollama APIs. Features include contextual memory retrieval, memory decay and reinforcement, hierarchical clustering, and graph-based associations.

## Features

- **Short-term and Long-term Memory**: Manages memory as short-term or long-term based on usage and relevance.

- **Contextual Retrieval**: Retrieves memories based on embeddings, concepts, and past interactions.

- **Concept Extraction and Embeddings**: Uses OpenAI or Ollama models for concept extraction and embedding generation.

- **Graph-Based Associations**: Builds a concept graph and uses spreading activation for relevance-based retrieval.

- **Hierarchical Clustering**: Clusters similar memories into semantic groups to aid in contextually relevant retrieval.

- **Decay and Reinforcement**: Older memories decay over time, while frequently accessed memories are reinforced.

## Installation

You can install Memoripy with pip:

```bash
pip install memoripy
```

## Usage
The following example demonstrates how to set up and use Memoripy in a Python script.

### Example: `example.py`
This example script shows the primary functionality of Memoripy, including initialization, storing interactions, retrieving relevant memories, and generating responses.

```bash
from memoripy import MemoryManager, JSONStorage

def main():
    # Replace 'your-api-key' with your actual OpenAI API key
    api_key = "your-key"
    if not api_key:
        raise ValueError("Please set your OpenAI API key.")

    # Define chat and embedding models
    chat_model = "openai"           # Choose 'openai' or 'ollama' for chat
    chat_model_name = "gpt-4o-mini" # Specific chat model name
    embedding_model = "ollama"      # Choose 'openai' or 'ollama' for embeddings
    embedding_model_name = "mxbai-embed-large"  # Specific embedding model name

    # Choose your storage option
    storage_option = JSONStorage("interaction_history.json")
    # Or use in-memory storage:
    # from memoripy import InMemoryStorage
    # storage_option = InMemoryStorage()

    # Initialize the MemoryManager with the selected models and storage
    memory_manager = MemoryManager(
        api_key=api_key,
        chat_model=chat_model,
        chat_model_name=chat_model_name,
        embedding_model=embedding_model,
        embedding_model_name=embedding_model_name,
        storage=storage_option
    )

    # New user prompt
    new_prompt = "My name is Khazar"

    # Load the last 5 interactions from history (for context)
    short_term, _ = memory_manager.load_history()
    last_interactions = short_term[-5:] if len(short_term) >= 5 else short_term

    # Retrieve relevant past interactions, excluding the last 5
    relevant_interactions = memory_manager.retrieve_relevant_interactions(new_prompt, exclude_last_n=5)

    # Generate a response using the last interactions and retrieved interactions
    response = memory_manager.generate_response(new_prompt, last_interactions, relevant_interactions)

    # Display the response
    print(f"Generated response:\n{response}")

    # Extract concepts for the new interaction
    combined_text = f"{new_prompt} {response}"
    concepts = memory_manager.extract_concepts(combined_text)

    # Store this new interaction along with its embedding and concepts
    new_embedding = memory_manager.get_embedding(combined_text)
    memory_manager.add_interaction(new_prompt, response, new_embedding, concepts)

if __name__ == "__main__":
    main()
```
## Classes and Modules
- `MemoryManager`: Manages memory interactions, retrieves relevant information, and generates responses based on past interactions.

- `MemoryStore`: Stores and organizes interactions in short-term and long-term memory, with support for clustering and retrieval based on relevance.

- `InMemoryStorage` and `JSONStorage`: Store memory in either in-memory data structures or JSON files.

- `BaseStorage`: Abstract base class for defining storage methods.

##Core Functionalities
1. **Initialize Memory**: Load previous interactions from the chosen storage and initialize memory.

2. **Add Interaction**: Store a new interaction with its embedding, concepts, prompt, and output.

3. **Retrieve Relevant Interactions**: Search past interactions based on a query using cosine similarity, decay factors, and spreading activation.

4. **Generate Response**: Combine the current prompt and retrieved interactions to generate a contextually relevant response.

5. **Decay and Reinforcement**: Increase decay on unused memories and reinforce frequently accessed memories.

## Requirements
Memoripy relies on several dependencies, including:

- `openai`

- `faiss-cpu`

- `numpy`

- `networkx`

- `scikit-learn`

- `langchain`

- `ollama`

These dependencies will be installed automatically with pip install memoripy.

## License
Memoripy is licensed under the MIT License.

## Contributing
Contributions are welcome! Feel free to open issues or submit pull requests for improvements.
