Memoripy: An AI Memory Layer for Context-Aware Applications
This repository profile is provided by osrepos.com, an open source repository discovery platform.

Summary
Memoripy is a Python library designed to provide an AI memory layer for context-aware applications. It offers both short-term and long-term storage, semantic clustering, and optional memory decay. This robust tool helps AI systems manage and retrieve relevant information efficiently, supporting various LLM APIs like OpenAI and Ollama.
Repository Information
Topics
Click on any tag to explore related repositories
Use at your own risk
OSRepos shares public repositories for knowledge and discovery only. Any installation, execution, configuration, or use of code from these repositories is the user's own responsibility. Always review the repository, source code, dependencies, licenses, and security implications before running or installing anything. OSRepos is not responsible for issues, damages, or losses resulting from third-party repositories.
Introdução
Memoripy é uma poderosa biblioteca Python que fornece uma camada avançada de memória de IA para aplicações que exigem gerenciamento de contexto sofisticado. Ela aborda o desafio de manter o estado conversacional e informações relevantes ao longo do tempo, oferecendo armazenamento de memória de curto e longo prazo. Projetada para aplicações orientadas por IA, Memoripy suporta integração perfeita com APIs populares de LLM, como OpenAI, Azure OpenAI, OpenRouter e Ollama, permitindo um gerenciamento inteligente de memória através de recursos como recuperação contextual, decaimento de memória e agrupamento hierárquico.
Instalação
Para começar com Memoripy, você pode instalá-lo facilmente usando pip:
pip install memoripy
Exemplos
O exemplo a seguir demonstra como inicializar MemoryManager, armazenar interações, recuperar memórias relevantes e gerar respostas usando Memoripy. Este script mostra a funcionalidade principal para construir aplicações de IA sensíveis ao contexto.
from memoripy import MemoryManager, JSONStorage
from memoripy.implemented_models import OpenAIChatModel, OllamaEmbeddingModel
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_name = "gpt-4o-mini" # Specific chat model name
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(
OpenAIChatModel(api_key, chat_model_name),
OllamaEmbeddingModel(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()
Este exemplo demonstra o ciclo de vida completo de uma interação, desde a inicialização e processamento do prompt até a geração da resposta e o armazenamento da memória.
Porquê usar Memoripy?
Memoripy oferece várias razões convincentes para desenvolvedores que constroem aplicações de IA:
- Gerenciamento de Memória Sofisticado: Ele distingue inteligentemente entre memória de curto e longo prazo, garantindo que o contexto seja sempre relevante e atualizado.
- Recuperação Contextual: Aproveitando embeddings, conceitos e associações baseadas em grafos, Memoripy recupera interações passadas altamente relevantes, melhorando significativamente a qualidade das respostas da IA.
- Memória Dinâmica: Recursos como decaimento e reforço da memória garantem que memórias mais antigas e menos relevantes desapareçam, enquanto memórias frequentemente acessadas e importantes são fortalecidas, imitando processos de memória naturais.
- Organização Semântica: O agrupamento hierárquico agrupa memórias semelhantes em grupos semânticos, tornando a recuperação mais eficiente e semanticamente coerente.
- Integração Flexível: Com suporte para múltiplas APIs de LLM e embeddings, Memoripy é adaptável a vários ecossistemas de IA e escolhas de modelos.
Links
Explore o repositório Memoripy no GitHub para mais detalhes, contribuições e atualizações:
Related repositories
Similar repositories that may be relevant next.

Griptape: Modular Python Framework for AI Agents and Workflows
July 5, 2026
Griptape is a modular Python framework designed to simplify the development of generative AI applications. It provides a flexible set of abstractions for working with Large Language Models (LLMs), Retrieval-Augmented Generation (RAG), and various other AI components. With its structured approach, Griptape enables developers to build sophisticated AI agents and workflows efficiently.

torchchat: Run PyTorch LLMs Locally on Servers, Desktop, and Mobile
July 3, 2026
torchchat is a PyTorch-native codebase designed to showcase the ability to run large language models (LLMs) seamlessly across various platforms. It enables local execution of LLMs using Python, within C/C++ applications on desktop or servers, and directly on iOS and Android devices. Although no longer under active development, it remains a valuable resource for understanding and implementing local LLM deployment strategies.

Docling: Streamline Document Processing for Generative AI Applications
July 3, 2026
Docling is a powerful Python library designed to simplify document processing, preparing diverse formats for generative AI applications. It offers advanced parsing capabilities, including sophisticated PDF understanding, and provides a unified document representation. With seamless integrations into the AI ecosystem, Docling empowers developers to build robust AI solutions.

DeepFabric: High-Quality Synthetic Data for Agentic AI Systems
July 2, 2026
DeepFabric is an open-source Python library designed to generate high-quality synthetic training data for language models and agent evaluations. It excels at creating domain-specific datasets that teach models to think, plan, and act effectively, including correct tool usage and adherence to schema structures. This comprehensive pipeline also integrates training and evaluation capabilities, ensuring robust model development.
Source repository
Open the original repository on GitHub.