Memoripy: An AI Memory Layer for Context-Aware Applications

This repository profile is provided by osrepos.com, an open source repository discovery platform.

Memoripy: An AI Memory Layer for Context-Aware Applications

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

Analyzed by OSRepos on July 5, 2026

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.

karpathy-llm-wiki: Build a Karpathy-Style LLM Knowledge Base

karpathy-llm-wiki: Build a Karpathy-Style LLM Knowledge Base

September 9, 2026

karpathy-llm-wiki is an Agent Skills-compatible tool that implements Karpathy's LLM Wiki idea, allowing users to build a durable knowledge base. It enables LLMs to maintain structured wiki pages by ingesting sources, compiling knowledge, and answering questions with citations. This project offers a robust alternative to traditional RAG for compounding knowledge over time.

llm-wikiknowledge-baseagent-skill
AgenticSchema: Empowering AI Agents with Structured Web Data

AgenticSchema: Empowering AI Agents with Structured Web Data

September 8, 2026

AgenticSchema is an innovative open-source library that transforms existing Schema.org markup, including JSON-LD, Microdata, and RDFa, into callable tools for AI agents. This library operates entirely client-side, requiring no backend infrastructure, and significantly enhances an agent's ability to interact with web content. By leveraging structured data already present on millions of websites, AgenticSchema bridges the gap between web content and AI agent capabilities.

aiai-agentsjson-ld
Context Engineering Kit: Enhance AI Agent Quality with Advanced Skills

Context Engineering Kit: Enhance AI Agent Quality with Advanced Skills

September 6, 2026

The Context Engineering Kit is a powerful collection of hand-crafted Claude Code Skills designed to significantly improve the quality and predictability of AI agent results. It offers advanced context engineering techniques with a minimal token footprint, ensuring efficiency and effectiveness across platforms like OpenCode, Cursor, and Gemini CLI. This kit provides granular control over plugins and includes an open-source alternative to CodeRabbit, enhancing development workflows.

agentaiclaude
opencode-worktree: Zero-Friction Git Worktrees for AI-Driven Development

opencode-worktree: Zero-Friction Git Worktrees for AI-Driven Development

September 6, 2026

opencode-worktree is an OpenCode plugin designed to streamline git worktree management. It automates the creation and deletion of isolated development environments, complete with terminal spawning and file synchronization. This tool is ideal for AI-driven workflows, offering a zero-friction experience for developers who prioritize automation and efficiency.

aiai-assistantgit

Source repository

Open the original repository on GitHub.

23 counted GitHub visits

View on GitHub
OS
OSRepos

Analysis and discovery of open source repositories. Find interesting projects and follow their updates.

Monitor your website with YourWebsiteScore

OSRepos shares public repositories for knowledge and discovery only. Any installation, execution, configuration, or use of third-party repository code is at your own risk. Always review source code, dependencies, licenses, and security implications before running anything.

© 2025 OSRepos. Built with Nuxt 3 and lots of ❤️