### Run DynamoDB Example Source: https://github.com/caspianmoon/memoripy/blob/master/examples/dynamo/README.md Execute the example application to test the DynamoDB storage adapter. This command assumes your environment is configured to connect to either a local or AWS DynamoDB instance. ```shell python -m examples.dynamo.dynamo_example ``` -------------------------------- ### Install Memoripy Source: https://github.com/caspianmoon/memoripy/blob/master/README.md Install the Memoripy library using pip. This command will also install all necessary dependencies. ```bash pip install memoripy ``` -------------------------------- ### Start Local DynamoDB with Docker Compose Source: https://github.com/caspianmoon/memoripy/blob/master/examples/dynamo/README.md Use this command to start a local DynamoDB instance using Docker Compose for development. Ensure Docker Compose is installed and you are in the directory containing the `docker-compose.yml` file. ```shell docker compose up -d ``` -------------------------------- ### Initialize MemoryManager Source: https://context7.com/caspianmoon/memoripy/llms.txt Initialize the MemoryManager with specified chat and embedding models, and configure storage. This example uses OpenAI for chat and Ollama for embeddings, persisting data to a JSON file. ```python from memoripy import MemoryManager, JSONStorage from memoripy.implemented_models import OpenAIChatModel, OllamaEmbeddingModel # Initialize with OpenAI chat + Ollama embeddings, persisted to JSON memory_manager = MemoryManager( OpenAIChatModel(api_key="sk-...", model_name="gpt-4o-mini"), OllamaEmbeddingModel(model_name="mxbai-embed-large"), storage=JSONStorage("interaction_history.json") ) # Output: Memory initialized with N interactions in short-term and M in long-term. ``` -------------------------------- ### Generate LLM response with memory context Source: https://context7.com/caspianmoon/memoripy/llms.txt Builds a prompt with immediate and relevant context, then calls the chat model. Use this to get a response from the LLM incorporating memory. ```python new_prompt = "Can you summarize what you know about me so far?" short_term, _ = memory_manager.load_history() last_interactions = short_term[-5:] if len(short_term) >= 5 else short_term relevant = memory_manager.retrieve_relevant_interactions(new_prompt, exclude_last_n=5) response = memory_manager.generate_response( prompt=new_prompt, last_interactions=last_interactions, retrievals=relevant, context_window=3 # use at most 3 interactions from each source ) print(f"Response: {response}") # Response: "Based on our conversation, your name is Alice and you work in machine learning..." ``` -------------------------------- ### Initialize MemoryManager with JSONStorage Source: https://context7.com/caspianmoon/memoripy/llms.txt Set up the MemoryManager using JSON file-based persistence. Interactions are saved to the specified file. ```python from memoripy import MemoryManager, JSONStorage from memoripy.implemented_models import OpenAIChatModel, OllamaEmbeddingModel storage = JSONStorage("interaction_history.json") memory_manager = MemoryManager( OpenAIChatModel("sk-.", "gpt-4o-mini"), OllamaEmbeddingModel("mxbai-embed-large"), storage=storage ) ``` -------------------------------- ### Initialize MemoryManager with InMemoryStorage Source: https://context7.com/caspianmoon/memoripy/llms.txt Set up the MemoryManager using an in-memory storage backend. This is ephemeral and offers no persistence. ```python from memoripy import MemoryManager, InMemoryStorage from memoripy.implemented_models import OpenAIChatModel, OllamaEmbeddingModel memory_manager = MemoryManager( OpenAIChatModel("sk-.", "gpt-4o-mini"), OllamaEmbeddingModel("mxbai-embed-large"), storage=InMemoryStorage() ) ``` -------------------------------- ### Initialize and Use MemoryManager Source: https://github.com/caspianmoon/memoripy/blob/master/README.md Demonstrates initializing the MemoryManager with OpenAI chat and Ollama embedding models, using JSONStorage, and performing core memory operations like retrieving interactions and generating responses. Ensure your API key is set. ```python 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() ``` -------------------------------- ### Initialize OpenAI Chat Model Source: https://context7.com/caspianmoon/memoripy/llms.txt Instantiate the OpenAI chat model. Requires an API key and allows specifying the model name. ```python from memoripy.implemented_models import OpenAIChatModel chat_model = OpenAIChatModel( api_key="sk-.", model_name="gpt-4o-mini" # default: "gpt-3.5-turbo" ) ``` -------------------------------- ### Initialize Ollama Chat Model Source: https://context7.com/caspianmoon/memoripy/llms.txt Instantiate the Ollama chat model for local use. Specify the model name. ```python from memoripy.implemented_models import OllamaChatModel chat_model = OllamaChatModel(model_name="llama3.1:8b") # default: "llama3.1:8b" ``` -------------------------------- ### Initialize Generic OpenAI-compatible Chat Model Source: https://context7.com/caspianmoon/memoripy/llms.txt Instantiate a chat model for any OpenAI-compatible endpoint. Requires the API endpoint, API key, and model name. ```python from memoripy.implemented_models import ChatCompletionsModel chat_model = ChatCompletionsModel( api_endpoint="https://openrouter.ai/api/v1", api_key="sk-or-.", model_name="nousresearch/hermes-3-llama-3.1-405b:free" ) ``` -------------------------------- ### Initialize Azure OpenAI Chat Model Source: https://context7.com/caspianmoon/memoripy/llms.txt Instantiate the Azure-hosted OpenAI chat model. Requires API key, API version, Azure endpoint, and model name. ```python from memoripy.implemented_models import AzureOpenAIChatModel chat_model = AzureOpenAIChatModel( api_key="...", api_version="2024-10-21", azure_endpoint="https://my-resource.openai.azure.com/", model_name="gpt-4o-mini-2024-07-18" ) ``` -------------------------------- ### Initialize OpenRouter Chat Model Source: https://context7.com/caspianmoon/memoripy/llms.txt Instantiate the OpenRouter chat model, which acts as a multi-model gateway. Requires an API key and model name. ```python from memoripy.implemented_models import OpenRouterChatModel chat_model = OpenRouterChatModel( api_key="sk-or-.", model_name="nousresearch/hermes-3-llama-3.1-405b:free" ) ``` -------------------------------- ### Initialize Azure OpenAI Embedding Model Source: https://context7.com/caspianmoon/memoripy/llms.txt Instantiate the Azure-hosted OpenAI embedding model. Requires API key, API version, Azure endpoint, and model name. ```python from memoripy.implemented_models import AzureOpenAIEmbeddingModel embedding_model = AzureOpenAIEmbeddingModel( api_key="...", api_version="2024-10-21", azure_endpoint="https://my-resource.openai.azure.com/", model_name="text-embedding-3-small" ) ``` -------------------------------- ### Custom Redis Storage Backend Source: https://context7.com/caspianmoon/memoripy/llms.txt Implement a custom storage backend using Redis by extending BaseStorage. Requires implementing load_history and save_memory_to_history. ```python from memoripy import BaseStorage from memoripy.memory_store import MemoryStore import redis, json class RedisStorage(BaseStorage): def __init__(self, redis_url: str, key: str): self.client = redis.from_url(redis_url) self.key = key def load_history(self): raw = self.client.get(self.key) if raw is None: return [], [] data = json.loads(raw) return data.get("short_term_memory", []), data.get("long_term_memory", []) def save_memory_to_history(self, memory_store: MemoryStore): history = {"short_term_memory": [], "long_term_memory": []} for idx in range(len(memory_store.short_term_memory)): history["short_term_memory"].append({ "id": memory_store.short_term_memory[idx]["id"], "prompt": memory_store.short_term_memory[idx]["prompt"], "output": memory_store.short_term_memory[idx]["output"], "embedding": memory_store.embeddings[idx].flatten().tolist(), "timestamp": memory_store.timestamps[idx], "access_count": memory_store.access_counts[idx], "concepts": list(memory_store.concepts_list[idx]), "decay_factor": memory_store.short_term_memory[idx].get("decay_factor", 1.0), }) for interaction in memory_store.long_term_memory: history["long_term_memory"].append(interaction) self.client.set(self.key, json.dumps(history)) ``` -------------------------------- ### Initialize OpenAI Embedding Model Source: https://context7.com/caspianmoon/memoripy/llms.txt Instantiate the OpenAI text embedding model. Requires an API key and specifies the model name. ```python from memoripy.implemented_models import OpenAIEmbeddingModel embedding_model = OpenAIEmbeddingModel( api_key="sk-.", model_name="text-embedding-3-small" # only supported model ) ``` -------------------------------- ### MemoryManager Initialization Source: https://context7.com/caspianmoon/memoripy/llms.txt Initializes the MemoryManager with specified chat and embedding models, and a storage backend. It loads existing history and prepares the memory system. ```APIDOC ## MemoryManager Initialization ### Description Initializes the `MemoryManager` by connecting a chat model, an embedding model, and a storage backend. It handles loading existing interaction history, standardizing embedding dimensions, and clustering interactions. ### Method ```python MemoryManager(chat_model, embedding_model, storage) ``` ### Parameters - **chat_model**: An instance of a chat model (e.g., `OpenAIChatModel`). - **embedding_model**: An instance of an embedding model (e.g., `OllamaEmbeddingModel`). - **storage**: An instance of a storage backend (e.g., `JSONStorage`). ### Request Example ```python from memoripy import MemoryManager, JSONStorage from memoripy.implemented_models import OpenAIChatModel, OllamaEmbeddingModel # Initialize with OpenAI chat + Ollama embeddings, persisted to JSON memory_manager = MemoryManager( OpenAIChatModel(api_key="sk-...", model_name="gpt-4o-mini"), OllamaEmbeddingModel(model_name="mxbai-embed-large"), storage=JSONStorage("interaction_history.json") ) ``` ### Response Initializes the memory manager. Output indicates the number of interactions loaded. ### Response Example ``` Memory initialized with N interactions in short-term and M in long-term. ``` ``` -------------------------------- ### Initialize Ollama Embedding Model Source: https://context7.com/caspianmoon/memoripy/llms.txt Instantiate the Ollama embedding model for local use. The dimension is auto-detected. ```python from memoripy.implemented_models import OllamaEmbeddingModel embedding_model = OllamaEmbeddingModel(model_name="mxbai-embed-large") # Dimension is auto-detected by running a test embedding at initialization ``` -------------------------------- ### DynamoDB Storage Configuration Source: https://context7.com/caspianmoon/memoripy/llms.txt Configure DynamoDB storage using environment variables. Each set_id creates an independent memory partition, suitable for multi-user applications. ```python import os from memoripy import MemoryManager from memoripy.dynamo_storage import DynamoStorage from memoripy.implemented_models import AzureOpenAIChatModel, AzureOpenAIEmbeddingModel # Configure via environment variables: # MEMORIPY_DYNAMO_REGION (default: "us-east-1") # MEMORIPY_DYNAMO_HOST (optional, for local DynamoDB) # MEMORIPY_DYNAMO_READ_CAPACITY (default: "1") # MEMORIPY_DYNAMO_WRITE_CAPACITY (default: "1") # Each set_id creates/loads an independent memory partition — ideal for multi-user apps storage = DynamoStorage(set_id="user-alice-123") memory_manager = MemoryManager( AzureOpenAIChatModel("key", "2024-10-21", "https://resource.openai.azure.com/", "gpt-4o-mini-2024-07-18"), AzureOpenAIEmbeddingModel("key", "2024-10-21", "https://resource.openai.azure.com/", "text-embedding-3-small"), storage=storage ) ``` -------------------------------- ### OpenAIChatModel Source: https://context7.com/caspianmoon/memoripy/llms.txt Implementation for interacting with OpenAI's chat models. Allows specifying the API key and the desired model name. ```APIDOC ### `OpenAIChatModel` — OpenAI API chat and concept extraction ```python from memoripy.implemented_models import OpenAIChatModel chat_model = OpenAIChatModel( api_key="sk-...", model_name="gpt-4o-mini" # default: "gpt-3.5-turbo" ) ``` #### Parameters - **api_key** (str) - Required - Your OpenAI API key. - **model_name** (str) - Optional - The name of the OpenAI model to use (default: "gpt-3.5-turbo"). ``` -------------------------------- ### AzureOpenAIChatModel Source: https://context7.com/caspianmoon/memoripy/llms.txt Implementation for interacting with Azure-hosted OpenAI chat models. Requires API key, API version, Azure endpoint, and model name. ```APIDOC ### `AzureOpenAIChatModel` — Azure-hosted OpenAI chat ```python from memoripy.implemented_models import AzureOpenAIChatModel chat_model = AzureOpenAIChatModel( api_key="...", api_version="2024-10-21", azure_endpoint="https://my-resource.openai.azure.com/", model_name="gpt-4o-mini-2024-07-18" ) ``` #### Parameters - **api_key** (str) - Required - Your Azure OpenAI API key. - **api_version** (str) - Required - The API version to use. - **azure_endpoint** (str) - Required - The Azure OpenAI endpoint. - **model_name** (str) - Required - The name of the Azure OpenAI model. ``` -------------------------------- ### Complete End-to-End Conversation Loop Source: https://context7.com/caspianmoon/memoripy/llms.txt A full conversation loop demonstrating loading history, retrieving relevant interactions, generating a response, and storing the new interaction. Uses JSONStorage for persistence. ```python from memoripy import MemoryManager, JSONStorage from memoripy.implemented_models import OpenAIChatModel, OllamaEmbeddingModel def chat_turn(memory_manager: MemoryManager, user_input: str) -> str: # 1. Load recent history for immediate context short_term, _ = memory_manager.load_history() last_interactions = short_term[-5:] if len(short_term) >= 5 else short_term # 2. Retrieve semantically relevant past interactions relevant = memory_manager.retrieve_relevant_interactions( user_input, similarity_threshold=40, exclude_last_n=5 ) # 3. Generate a response grounded in memory context response = memory_manager.generate_response( user_input, last_interactions, relevant, context_window=3 ) # 4. Embed and store the new interaction combined = f"{user_input} {response}" embedding = memory_manager.get_embedding(combined) concepts = memory_manager.extract_concepts(combined) memory_manager.add_interaction(user_input, response, embedding, concepts) return response if __name__ == "__main__": manager = MemoryManager( OpenAIChatModel("sk-...", "gpt-4o-mini"), OllamaEmbeddingModel("mxbai-embed-large"), storage=JSONStorage("chat_history.json") ) turns = [ "My name is Alice and I'm a data scientist.", "I'm working on a recommendation system using collaborative filtering.", "What do you know about me?", ] for turn in turns: reply = chat_turn(manager, turn) print(f"User: {turn}") print(f"Agent: {reply}\n") ``` -------------------------------- ### ChatCompletionsModel Source: https://context7.com/caspianmoon/memoripy/llms.txt A generic implementation for OpenAI-compatible chat completion endpoints. Requires the API endpoint, API key, and model name. ```APIDOC ### `ChatCompletionsModel` — Generic OpenAI-compatible endpoint ```python from memoripy.implemented_models import ChatCompletionsModel chat_model = ChatCompletionsModel( api_endpoint="https://openrouter.ai/api/v1", api_key="sk-or-...", model_name="nousresearch/hermes-3-llama-3.1-405b:free" ) ``` #### Parameters - **api_endpoint** (str) - Required - The URL of the OpenAI-compatible API endpoint. - **api_key** (str) - Required - The API key for the endpoint. - **model_name** (str) - Required - The name of the model to use. ``` -------------------------------- ### OpenRouterChatModel Source: https://context7.com/caspianmoon/memoripy/llms.txt Implementation for using the OpenRouter gateway to access various chat models. Requires an API key and the desired model name. ```APIDOC ### `OpenRouterChatModel` — OpenRouter multi-model gateway ```python from memoripy.implemented_models import OpenRouterChatModel chat_model = OpenRouterChatModel( api_key="sk-or-...", model_name="nousresearch/hermes-3-llama-3.1-405b:free" ) ``` #### Parameters - **api_key** (str) - Required - Your OpenRouter API key. - **model_name** (str) - Required - The name of the model to use on OpenRouter. ``` -------------------------------- ### MemoryManager.generate_response() Source: https://context7.com/caspianmoon/memoripy/llms.txt Generates a response from a chat model by incorporating immediate context window and retrieved relevant interactions. It builds a prompt using these elements and returns the model's string response. ```APIDOC ## `MemoryManager.generate_response()` — Generate an LLM response with memory context Builds a prompt incorporating the last N interactions (immediate context window) and the retrieved relevant interactions, then calls the chat model. Returns the model's string response. ### Parameters - **prompt** (str) - Required - The user's input prompt. - **last_interactions** (list) - Required - A list of the most recent interactions. - **retrievals** (list) - Required - A list of relevant interactions retrieved from memory. - **context_window** (int) - Optional - The maximum number of interactions to use from each source (e.g., last_interactions, retrievals). ### Request Example ```python new_prompt = "Can you summarize what you know about me so far?" short_term, _ = memory_manager.load_history() last_interactions = short_term[-5:] if len(short_term) >= 5 else short_term relevant = memory_manager.retrieve_relevant_interactions(new_prompt, exclude_last_n=5) response = memory_manager.generate_response( prompt=new_prompt, last_interactions=last_interactions, retrievals=relevant, context_window=3 # use at most 3 interactions from each source ) print(f"Response: {response}") # Response: "Based on our conversation, your name is Alice and you work in machine learning..." ``` ``` -------------------------------- ### MemoryManager.load_history() Source: https://context7.com/caspianmoon/memoripy/llms.txt Loads stored interactions from the configured storage backend, returning both short-term and long-term memory. ```APIDOC ## MemoryManager.load_history() ### Description Loads stored interactions from the configured storage backend. This method is useful for seeding the recent-context window before generating a response by providing access to both short-term and long-term memory. ### Method ```python memory_manager.load_history() ``` ### Parameters None ### Response Returns a tuple containing two lists: `(short_term, long_term)`, where each list contains interaction dictionaries. ### Response Example ```python short_term, long_term = memory_manager.load_history() # Use the last 5 interactions as immediate context last_interactions = short_term[-5:] if len(short_term) >= 5 else short_term print(f"Short-term: {len(short_term)} interactions") print(f"Long-term: {len(long_term)} interactions") # Output: # Short-term: 12 interactions # Long-term: 3 interactions ``` ``` -------------------------------- ### OpenAIEmbeddingModel Source: https://context7.com/caspianmoon/memoripy/llms.txt Implementation for generating text embeddings using OpenAI's models. Requires an API key and the model name. ```APIDOC ### `OpenAIEmbeddingModel` — OpenAI text embeddings (1536-dim) ```python from memoripy.implemented_models import OpenAIEmbeddingModel embedding_model = OpenAIEmbeddingModel( api_key="sk-...", model_name="text-embedding-3-small" # only supported model ) ``` #### Parameters - **api_key** (str) - Required - Your OpenAI API key. - **model_name** (str) - Optional - The name of the OpenAI embedding model to use (default: "text-embedding-3-small"). ``` -------------------------------- ### OllamaChatModel Source: https://context7.com/caspianmoon/memoripy/llms.txt Implementation for interacting with local Ollama chat models. Requires specifying the model name. ```APIDOC ### `OllamaChatModel` — Local Ollama chat and concept extraction ```python from memoripy.implemented_models import OllamaChatModel chat_model = OllamaChatModel(model_name="llama3.1:8b") # default: "llama3.1:8b" ``` #### Parameters - **model_name** (str) - Optional - The name of the Ollama model to use (default: "llama3.1:8b"). ``` -------------------------------- ### InMemoryStorage Source: https://context7.com/caspianmoon/memoripy/llms.txt An ephemeral in-process storage backend that does not persist data. Useful for testing or short-lived memory needs. ```APIDOC ### `InMemoryStorage` — Ephemeral in-process storage (no persistence) ```python from memoripy import MemoryManager, InMemoryStorage from memoripy.implemented_models import OpenAIChatModel, OllamaEmbeddingModel memory_manager = MemoryManager( OpenAIChatModel("sk-", "gpt-4o-mini"), OllamaEmbeddingModel("mxbai-embed-large"), storage=InMemoryStorage() ) ``` #### Parameters This storage backend does not require any specific parameters during initialization. ``` -------------------------------- ### JSONStorage Source: https://context7.com/caspianmoon/memoripy/llms.txt A file-based storage backend that persists memory interactions to a JSON file. This allows for data persistence across application runs. ```APIDOC ### `JSONStorage` — File-based JSON persistence ```python from memoripy import MemoryManager, JSONStorage from memoripy.implemented_models import OpenAIChatModel, OllamaEmbeddingModel storage = JSONStorage("interaction_history.json") memory_manager = MemoryManager( OpenAIChatModel("sk-", "gpt-4o-mini"), OllamaEmbeddingModel("mxbai-embed-large"), storage=storage ) ``` #### Parameters - **file_path** (str) - Required - The path to the JSON file where interactions will be stored. ``` -------------------------------- ### AzureOpenAIEmbeddingModel Source: https://context7.com/caspianmoon/memoripy/llms.txt Implementation for generating text embeddings using Azure-hosted OpenAI models. Requires API key, API version, Azure endpoint, and model name. ```APIDOC ### `AzureOpenAIEmbeddingModel` — Azure-hosted OpenAI embeddings ```python from memoripy.implemented_models import AzureOpenAIEmbeddingModel embedding_model = AzureOpenAIEmbeddingModel( api_key="...", api_version="2024-10-21", azure_endpoint="https://my-resource.openai.azure.com/", model_name="text-embedding-3-small" ) ``` #### Parameters - **api_key** (str) - Required - Your Azure OpenAI API key. - **api_version** (str) - Required - The API version to use. - **azure_endpoint** (str) - Required - The Azure OpenAI endpoint. - **model_name** (str) - Required - The name of the Azure OpenAI embedding model. ``` -------------------------------- ### Persist new interaction to memory Source: https://context7.com/caspianmoon/memoripy/llms.txt Stores a prompt/response pair with its embedding and concepts. Automatically promotes to long-term memory when access count exceeds 10. Ensure you have generated the response, embedding, and concepts before calling this. ```python new_prompt = "My name is Alice" response = memory_manager.generate_response(new_prompt, last_interactions, relevant) combined_text = f"{new_prompt} {response}" embedding = memory_manager.get_embedding(combined_text) concepts = memory_manager.extract_concepts(combined_text) memory_manager.add_interaction( prompt=new_prompt, output=response, embedding=embedding, concepts=concepts ) # Adding new interaction to short-term memory: 'My name is Alice' # Total interactions stored in short-term memory: 13 # Saved interaction history to JSON. Short-term: 13, Long-term: 3 ``` -------------------------------- ### MemoryManager.add_interaction() Source: https://context7.com/caspianmoon/memoripy/llms.txt Persists a new interaction (prompt and response pair) to memory. It stores the interaction with its embedding and extracted concepts, automatically promoting it to long-term memory if its access count exceeds a threshold. ```APIDOC ## `MemoryManager.add_interaction()` — Persist a new interaction to memory Stores a prompt/response pair along with its embedding and extracted concepts into the `MemoryStore` and immediately syncs to the configured storage backend. Automatically promotes interactions to long-term memory when their `access_count` exceeds 10. ### Parameters - **prompt** (str) - Required - The user's prompt. - **output** (str) - Required - The model's response. - **embedding** (list[float]) - Required - The embedding vector for the interaction. - **concepts** (list[str]) - Required - A list of concepts extracted from the interaction. ### Request Example ```python new_prompt = "My name is Alice" response = memory_manager.generate_response(new_prompt, last_interactions, relevant) combined_text = f"{new_prompt} {response}" embedding = memory_manager.get_embedding(combined_text) concepts = memory_manager.extract_concepts(combined_text) memory_manager.add_interaction( prompt=new_prompt, output=response, embedding=embedding, concepts=concepts ) # Adding new interaction to short-term memory: 'My name is Alice' # Total interactions stored in short-term memory: 13 # Saved interaction history to JSON. Short-term: 13, Long-term: 3 ``` ``` -------------------------------- ### OllamaEmbeddingModel Source: https://context7.com/caspianmoon/memoripy/llms.txt Implementation for generating text embeddings using local Ollama models. The embedding dimension is auto-detected. ```APIDOC ### `OllamaEmbeddingModel` — Local Ollama embeddings (auto-detected dim) ```python from memoripy.implemented_models import OllamaEmbeddingModel embedding_model = OllamaEmbeddingModel(model_name="mxbai-embed-large") # Dimension is auto-detected by running a test embedding at initialization ``` #### Parameters - **model_name** (str) - Optional - The name of the Ollama embedding model to use (default: "mxbai-embed-large"). ``` -------------------------------- ### Load Interaction History Source: https://context7.com/caspianmoon/memoripy/llms.txt Load stored interactions from the configured storage backend. This function returns both short-term and long-term memories, useful for populating the context window. ```python short_term, long_term = memory_manager.load_history() # Use the last 5 interactions as immediate context last_interactions = short_term[-5:] if len(short_term) >= 5 else short_term print(f"Short-term: {len(short_term)} interactions") print(f"Long-term: {len(long_term)} interactions") # Short-term: 12 interactions # Long-term: 3 interactions ``` -------------------------------- ### MemoryManager.extract_concepts() Source: https://context7.com/caspianmoon/memoripy/llms.txt Extracts key concepts from a given text using the configured chat model. ```APIDOC ## MemoryManager.extract_concepts() ### Description Extracts a list of semantically meaningful concept strings from the provided text by invoking the chat model with a structured prompt. These extracted concepts are used in the graph-based spreading activation process during retrieval scoring. ### Method ```python memory_manager.extract_concepts(text) ``` ### Parameters - **text** (string): The input text from which to extract concepts. ### Response Returns a list of strings, where each string is a key concept extracted from the text. ### Response Example ```python text = "Alice discussed transformer architectures and attention mechanisms in NLP." concepts = memory_manager.extract_concepts(text) print(concepts) # Output: # ['transformer architectures', 'attention mechanisms', 'NLP', 'Alice'] ``` ``` -------------------------------- ### MemoryManager.retrieve_relevant_interactions() Source: https://context7.com/caspianmoon/memoripy/llms.txt Retrieves past interactions that are relevant to a given query, considering similarity, time decay, and concept spreading activation. ```APIDOC ## MemoryManager.retrieve_relevant_interactions() ### Description Retrieves past interactions relevant to a query. It embeds the query, scores all short-term interactions using adjusted cosine similarity (incorporating time decay and access-count reinforcement), and performs spreading activation on the concept graph. Interactions exceeding a specified similarity threshold are returned, sorted by their total score. The `exclude_last_n` parameter can be used to omit the most recent interactions from the results. ### Method ```python memory_manager.retrieve_relevant_interactions(query, similarity_threshold=None, exclude_last_n=0) ``` ### Parameters - **query** (string): The user's query for which to find relevant interactions. - **similarity_threshold** (integer, optional): The minimum adjusted score (on a 0–100 scale) required for an interaction to be considered relevant. Defaults to None. - **exclude_last_n** (integer, optional): The number of most recent interactions to exclude from the retrieval results. Defaults to 0. ### Response Returns a list of dictionaries, where each dictionary represents a relevant interaction. Each interaction dictionary includes details like 'prompt', 'output', and 'total_score'. ### Response Example ```python query = "What did we discuss about deep learning?" relevant = memory_manager.retrieve_relevant_interactions( query, similarity_threshold=40, # minimum adjusted score (0–100 scale) exclude_last_n=5 # skip the 5 most recent interactions ) for interaction in relevant: print(f"[score={interaction.get('total_score', 'n/a'):.2f}]") print(f" Prompt: {interaction['prompt']}") print(f" Output: {interaction['output'][:80]}...") ``` ``` -------------------------------- ### Extract Concepts from Text Source: https://context7.com/caspianmoon/memoripy/llms.txt Extract key concepts from text using the chat model. These concepts are used in the graph-based spreading activation for retrieval scoring. ```python text = "Alice discussed transformer architectures and attention mechanisms in NLP." concepts = memory_manager.extract_concepts(text) print(concepts) # ['transformer architectures', 'attention mechanisms', 'NLP', 'Alice'] ``` -------------------------------- ### Retrieve Relevant Interactions Source: https://context7.com/caspianmoon/memoripy/llms.txt Retrieve past interactions relevant to a query. This method scores interactions using similarity, time decay, and reinforcement, then applies spreading activation. ```python query = "What did we discuss about deep learning?" relevant = memory_manager.retrieve_relevant_interactions( query, similarity_threshold=40, # minimum adjusted score (0–100 scale) exclude_last_n=5 # skip the 5 most recent interactions ) for interaction in relevant: print(f"[score={interaction.get('total_score', 'n/a'):.2f}]") print(f" Prompt: {interaction['prompt']}") print(f" Output: {interaction['output'][:80]}...") ``` -------------------------------- ### MemoryManager.get_embedding() Source: https://context7.com/caspianmoon/memoripy/llms.txt Generates a vector embedding for a given piece of text using the configured embedding model. ```APIDOC ## MemoryManager.get_embedding() ### Description Generates a vector embedding for the provided text using the configured `EmbeddingModel`. The embedding is then standardized to the manager's target dimension by padding or truncating as needed. The output is a `(1, dim)` shaped numpy array suitable for FAISS and cosine similarity operations. ### Method ```python memory_manager.get_embedding(text) ``` ### Parameters - **text** (string): The input text for which to generate an embedding. ### Response Returns a numpy array representing the standardized vector embedding of the input text. ### Response Example ```python text = "My name is Alice and I work in machine learning." embedding = memory_manager.get_embedding(text) print(f"Embedding shape: {embedding.shape}") # (1, 1536) print(f"Embedding dtype: {embedding.dtype}") # float32 ``` ``` -------------------------------- ### Generate Text Embedding Source: https://context7.com/caspianmoon/memoripy/llms.txt Generate a vector embedding for a given text using the configured EmbeddingModel. The embedding is standardized to the manager's target dimension and shaped for similarity operations. ```python text = "My name is Alice and I work in machine learning." embedding = memory_manager.get_embedding(text) print(f"Embedding shape: {embedding.shape}") # (1, 1536) print(f"Embedding dtype: {embedding.dtype}") # float32 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.