### Development Setup for OntoMem Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/quick-start.md Sets up the OntoMem development environment by cloning the repository and installing development dependencies using uv. This is useful for contributing to OntoMem or working with its source code. ```bash git clone https://github.com/yifanfeng97/ontomem.git cd ontomem # Install with dev dependencies uv sync --group dev ``` -------------------------------- ### Install OntoMem from Source (Development) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/installation.md Installs OntoMem in development mode from its source code repository. This involves cloning the repository and then installing it using 'uv' or 'pip'. This method is suitable for developers contributing to OntoMem. ```bash # Clone the repository git clone https://github.com/yifanfeng97/ontomem.git cd ontomem # Install in development mode uv sync --group dev # Or with pip pip install -e . ``` -------------------------------- ### Install Development Tools for OntoMem Contribution Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/installation.md Installs a suite of development tools required for contributing to OntoMem. This includes linters, formatters, documentation generators, and testing frameworks, managed using 'uv'. ```bash uv sync --group dev ``` -------------------------------- ### Verify OntoMem Installation (Command Line) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/installation.md Verifies the OntoMem installation by checking its version number directly from the command line using a short Python script. This confirms that the package is installed and importable. ```bash python -c "import ontomem; print(ontomem.__version__)" ``` -------------------------------- ### Install OntoMem via uv Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/installation.md Installs OntoMem using 'uv', a fast and modern Python package manager. This method is recommended for developers. It also includes instructions for installing uv itself if not already present. ```bash # Install uv if not already installed curl https://astral.sh/uv/install.sh | sh # Install ontomem uv add ontomem ``` -------------------------------- ### Install OntoMem using pip Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/quick-start.md Installs the OntoMem library using pip, a common Python package installer. This is a straightforward method for adding OntoMem to your project's dependencies. ```bash pip install ontomem ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/installation.md Demonstrates how to create and activate a Python virtual environment using the 'venv' module. This is a recommended practice for managing project dependencies and avoiding conflicts. ```bash # Create virtual environment python -m venv .venv # Activate source .venv/bin/activate # On Windows: .venv\Scripts\activate # Install ontomem pip install ontomem ``` -------------------------------- ### Install Optional Dependencies for LLM Features Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/installation.md Installs the necessary packages ('langchain' and 'langchain-openai') to enable LLM-based merge strategies within OntoMem. These are optional and only required if you plan to use these advanced features. ```bash pip install langchain langchain-openai ``` -------------------------------- ### Verify OntoMem Installation (Python) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/installation.md Verifies a successful OntoMem installation by importing core components ('OMem', 'MergeStrategy') and printing a success message. This is a quick check to ensure the package is accessible. ```python from ontomem import OMem, MergeStrategy print("✅ OntoMem installed successfully!") ``` -------------------------------- ### Run Python Examples for OntoMem Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/examples/examples-overview.md Demonstrates how to execute various OntoMem examples written in Python. This includes navigating to the examples directory and running individual Python scripts for different functionalities. ```bash cd examples/ python 01_self_improving_debugger.py python 02_rpg_npc_memory.py python 03_semantic_scholar.py python 04_multi_source_fusion.py python 05_conversation_history.py python 06_temporal_memory_consolidation.py # For Chinese versions cd zh/ python 01_self_improving_debugger.py ``` -------------------------------- ### Troubleshoot FAISS ImportError (CPU) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/installation.md Provides the command to install the CPU-only version of FAISS if the 'ImportError: FAISS not found' occurs. This is a fallback for systems without GPU support or when GPU installation fails. ```bash pip install faiss-cpu ``` -------------------------------- ### Running the Multi-Source Fusion Example (Bash) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/examples/04-multi-source-fusion.md Provides instructions to navigate to the examples directory, set an optional OpenAI API key, and run the multi-source fusion Python script. ```bash cd examples/ # Set your OpenAI API key (optional, will fallback without it) export OPENAI_API_KEY="your-key-here" python 04_multi_source_fusion.py ``` -------------------------------- ### Build Documentation (Bash) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/faq.md Commands to install necessary packages for documentation generation and serve the documentation locally for preview. ```bash uv add --group dev mkdocs mkdocs-material mkdocs serve ``` -------------------------------- ### Bash Commands for Running OMem Examples Source: https://github.com/yifanfeng97/ontomem/blob/main/examples/EXAMPLES.md Provides bash commands to execute OMem examples, test them individually or all at once, and inspect the generated memory files. These commands are useful for development and debugging. ```bash # Test single example python examples/01_self_improving_debugger.py ``` ```bash # Test all examples with timing time for i in {1..5}; do python examples/0${i}_*.py > /dev/null 2>&1; done ``` ```bash # Check generated memory files ls -la temp/*/memory.json ``` ```bash # View specific memory cat temp/debugger_memory.json/memory.json | python -m json.tool | head -20 ``` -------------------------------- ### Production Example: Dynamic max_workers Configuration Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/user-guide/merge-strategies.md Illustrates a production-ready example where `max_workers` is read from an environment variable (`ONTOMEM_MAX_WORKERS`), allowing dynamic adjustment without code changes. This enhances flexibility and manageability. ```python import os from ontomem import OMem, MergeStrategy # Read from environment for easy adjustment without code changes max_workers = int(os.getenv("ONTOMEM_MAX_WORKERS", "3")) memory = OMem( memory_schema=Profile, key_extractor=lambda x: x.id, llm_client=ChatOpenAI(model="gpt-4o"), embedder=OpenAIEmbeddings(), strategy_or_merger=MergeStrategy.LLM.BALANCED, max_workers=max_workers ) ``` -------------------------------- ### Running Temporal Memory Consolidation Example Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/examples/06-temporal-memory-consolidation.md Provides instructions to navigate to the examples directory and execute the Python script for temporal memory consolidation. It also shows how to set the OpenAI API key, which is optional but enhances LLM synthesis capabilities. ```bash cd examples/ # Set your OpenAI API key for LLM synthesis (optional) export OPENAI_API_KEY="your-key-here" python 06_temporal_memory_consolidation.py ``` -------------------------------- ### Install Ontomem Package Source: https://github.com/yifanfeng97/ontomem/blob/main/README.md This section provides instructions for installing the Ontomem Python package using pip or uv. It covers both basic installation and a command for setting up the development environment with all necessary tools for developers. ```bash pip install ontomem ``` ```bash uv add ontomem ``` ```bash uv sync --group dev ``` -------------------------------- ### Troubleshoot LangChain Version Issues Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/installation.md Ensures that the correct versions of LangChain and related packages are installed to avoid compatibility issues. This is important if using LLM-powered features that rely on LangChain. ```bash pip install "langchain>=1.2.1" "langchain-openai>=1.1.6" "langchain-community>=0.4.1" ``` -------------------------------- ### Running Semantic Scholar Example (Bash) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/examples/03-semantic-scholar.md Provides instructions to run the semantic scholar example. This involves navigating to the examples directory, setting the OpenAI API key as an environment variable, and executing the Python script. ```bash cd examples/ # Set your OpenAI API key export OPENAI_API_KEY="your-key-here" python 03_semantic_scholar.py ``` -------------------------------- ### Query Data from OntoMem by Key Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/quick-start.md Retrieves a specific researcher profile from OntoMem using the `get` method with the unique key (name). This demonstrates exact matching and accessing stored data. ```python # Get exact match researcher = memory.get("Yann LeCun") print(f"Found: {researcher.name}") print(f"Interests: {researcher.research_interests}") ``` -------------------------------- ### Running the Self-Improving Debugger Example (Bash) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/examples/01-self-improving-debugger.md Command to navigate to the examples directory and execute the self-improving debugger script. This initiates the AI debugging agent and its learning process. ```bash cd examples/ python 01_self_improving_debugger.py ``` -------------------------------- ### Demonstrate Auto-Consolidation in OntoMem Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/quick-start.md Illustrates OntoMem's auto-consolidation feature by adding fragmented information about 'Yann LeCun' over two 'days'. OntoMem automatically merges these updates based on the `MERGE_FIELD` strategy, resulting in a consolidated profile. ```python # Day 1: You learn about Yann LeCun memory.add(ResearcherProfile( name="Yann LeCun", affiliation="Meta AI", research_interests=["deep learning"], publications=["CNNs for Image Recognition"] )) # Day 2: New information about the same person memory.add(ResearcherProfile( name="Yann LeCun", affiliation="Meta AI", # Same research_interests=["convolutional networks"], # New detail publications=["Backpropagation Paper"] # Additional paper )) # Query the consolidated record profile = memory.get("Yann LeCun") print(profile.research_interests) # Output: ["deep learning", "convolutional networks"] # Output: ["CNNs for Image Recognition", "Backpropagation Paper"] ``` -------------------------------- ### Run Python OMem Examples Source: https://github.com/yifanfeng97/ontomem/blob/main/examples/README.md These bash commands demonstrate how to execute the OMem example scripts. They cover running individual English and Chinese examples, as well as batch execution for all examples in a language. ```bash # Run individual English examples python examples/01_self_improving_debugger.py python examples/02_rpg_npc_memory.py python examples/03_semantic_scholar.py python examples/04_multi_source_fusion.py python examples/05_conversation_history.py # Run individual Chinese examples python examples/zh/01_self_improving_debugger.py python examples/zh/02_rpg_npc_memory.py python examples/zh/03_semantic_scholar.py python examples/zh/04_multi_source_fusion.py python examples/zh/05_conversation_history.py # Run all English examples for i in {1..5}; do python examples/0${i}_*.py; done # Run all Chinese examples for file in examples/zh/*.py; do python "$file"; done ``` -------------------------------- ### Troubleshoot Pydantic Version Conflicts Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/installation.md Specifies the required Pydantic version (2.x or higher) for OntoMem and provides the command to install it. This addresses potential conflicts arising from older Pydantic versions. ```bash pip install "pydantic>=2.12.5" ``` -------------------------------- ### Setup LLM Client for OntoMem Strategies in Python Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/user-guide/merge-strategies.md Configures OntoMem to use LLM-powered merge strategies by initializing Langchain's ChatOpenAI and OpenAIEmbeddings clients. This setup is required for strategies like LLM.BALANCED. ```python from ontomem import OMem, MergeStrategy from langchain_openai import ChatOpenAI, OpenAIEmbeddings # Assuming Profile is a defined Pydantic model or similar # class Profile: # id: str # # ... other fields memory = OMem( memory_schema=Profile, key_extractor=lambda x: x.id, llm_client=ChatOpenAI(model="gpt-4o"), embedder=OpenAIEmbeddings(), strategy_or_merger=MergeStrategy.LLM.BALANCED ) ``` -------------------------------- ### Install FAISS Library (Bash) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/faq.md Provides commands to install the FAISS library, essential for certain memory operations. Supports both CPU and GPU versions. ```bash pip install faiss-cpu # or for GPU: pip install faiss-gpu ``` -------------------------------- ### Running the Conversation History Example (Bash) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/examples/05-conversation-history.md Provides the command to execute the conversation history example script. This script demonstrates the practical application of the ConversationMemory data structure and OntoMem's capabilities in managing dialogue context. ```bash cd examples/ python 05_conversation_history.py ``` -------------------------------- ### Running the RPG NPC Memory Example (Bash) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/examples/02-rpg-npc-memory.md Provides the command to navigate to the examples directory and execute the RPG NPC memory simulation script. This script demonstrates how OntoMem can be used to build and manage NPC memory over multiple player interactions. ```bash cd examples/ python 02_rpg_npc_memory.py ``` -------------------------------- ### Clone and Install Dependencies (Bash) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/contributing.md This snippet shows how to clone the OntoMem repository and install the necessary development dependencies using `uv`. ```bash git clone https://github.com/yifanfeng97/ontomem.git cd ontomem uv sync --group dev ``` -------------------------------- ### Initialize OntoMem Memory Instance Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/quick-start.md Initializes an OntoMem memory instance using a Pydantic schema, a key extractor function, an LLM client (ChatOpenAI), an embedder (OpenAIEmbeddings), and a merge strategy. This sets up the core components for managing memory. ```python from ontomem import OMem, MergeStrategy from langchain_openai import ChatOpenAI, OpenAIEmbeddings # Create memory instance memory = OMem( memory_schema=ResearcherProfile, key_extractor=lambda x: x.name, # Use name as unique key llm_client=ChatOpenAI(model="gpt-4o"), embedder=OpenAIEmbeddings(), strategy_or_merger=MergeStrategy.MERGE_FIELD # Start simple ) ``` -------------------------------- ### Save and Restore OntoMem Memory State Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/quick-start.md Demonstrates saving the entire OntoMem memory state to a file using `dump` and restoring it in a new Python session using `load`. This allows for persistence and continuation of memory across different runs. ```python # Save entire memory state memory.dump("./my_researcher_memory") # Later, in a new Python session: new_memory = OMem( memory_schema=ResearcherProfile, key_extractor=lambda x: x.name, llm_client=ChatOpenAI(model="gpt-4o"), embedder=OpenAIEmbeddings(), ) # Restore new_memory.load("./my_researcher_memory") # Continue working researcher = new_memory.get("Yann LeCun") print(researcher.research_interests) # Still there! ``` -------------------------------- ### Search, List Keys, and Remove Data in OntoMem Source: https://github.com/yifanfeng97/ontomem/blob/main/README.md Provides examples of common data retrieval and management operations in OntoMem. This includes exact retrieval by key, getting a list of all keys currently stored in memory, and removing specific records. ```python # Exact retrieval profile = memory.get("Alice") # All keys in memory all_keys = memory.keys # Clear or remove memory.remove("Alice") ``` -------------------------------- ### Build Index for Semantic Search in OntoMem Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/quick-start.md Builds a vector index for the OntoMem memory using the `build_index` method. This enables semantic search capabilities, allowing queries based on meaning rather than exact keywords. ```python # Build vector index memory.build_index() # Now search by semantic meaning results = memory.search("machine learning neural networks", top_k=5) for researcher in results: print(f"- {researcher.name}: {researcher.research_interests}") ``` -------------------------------- ### Basic OntoMem Usage Example Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/api/overview.md A fundamental example demonstrating how to initialize OMem with a Pydantic schema, a key extractor, and an embedder, then add and retrieve a researcher entity. ```python from ontomem import OMem, MergeStrategy from pydantic import BaseModel from langchain_openai import OpenAIEmbeddings class Researcher(BaseModel): name: str institution: str papers: list[str] memory = OMem( memory_schema=Researcher, key_extractor=lambda x: x.name, embedder=OpenAIEmbeddings(), merge_strategy=MergeStrategy.MERGE_FIELD ) memory.add(Researcher( name="Yann LeCun", institution="Meta AI", papers=["CNNs"] )) researcher = memory.get("Yann LeCun") print(researcher.papers) ``` -------------------------------- ### Integrate with LangChain LLMs Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/faq.md Provides examples of initializing different LLM models using LangChain. This includes models from OpenAI, Anthropic, and open-source models via Ollama. ```python # OpenAI from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-4o") # Anthropic from langchain_anthropic import ChatAnthropic llm = ChatAnthropic(model="claude-3-opus") # Ollama from langchain_community.chat_models import ChatOllama llm = ChatOllama(model="llama2") ``` -------------------------------- ### Install FAISS GPU Acceleration Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/faq.md Installs the FAISS library with GPU support for enhanced performance. This command is executed in a bash environment and requires an NVIDIA GPU. ```bash pip install faiss-gpu ``` -------------------------------- ### Time-Series Consolidation with Dynamic LLM Rule in Python Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/user-guide/merge-strategies.md Presents a time-series consolidation example using a dynamic LLM merge rule in Python. The `get_consolidation_context` function provides time-based instructions to the LLM for merging daily reports, adjusting the consolidation logic based on the day of the week. ```python from ontomem import OMem from ontomem.merger import create_merger, MergeStrategy from datetime import datetime from pydantic import BaseModel # Assuming BaseModel for schema definition # Assuming llm client is defined elsewhere # llm = ... class DailyReport(BaseModel): employee_id: str date: str tasks_completed: int mood: str def get_consolidation_context(): """Adjust consolidation based on report timing.""" now = datetime.now() day_name = now.strftime("%A") return f"Today is {day_name}. Mid-week reports should balance all tasks. End-of-week reports should summarize the whole week." # Composite key: employee_id + date for daily consolidation memory = OMem( memory_schema=DailyReport, key_extractor=lambda x: f"{x.employee_id}_{x.date}", merger=create_merger( strategy=MergeStrategy.LLM.CUSTOM_RULE, rule="Consolidate multiple daily updates into one coherent daily report. Sum task counts and synthesize mood description.", dynamic_rule=get_consolidation_context ), llm_client=llm ) ``` -------------------------------- ### Set OpenAI API Key for OMem Examples Source: https://github.com/yifanfeng97/ontomem/blob/main/examples/README.md This bash command demonstrates how to set the OPENAI_API_KEY environment variable, which is required for certain OMem examples like the Semantic Scholar, to function correctly. The key should be added to a .env file. ```bash # Add OPENAI_API_KEY to .env echo "OPENAI_API_KEY=sk-...". > ../.env ``` -------------------------------- ### Get Logger Instance and Log Info Message (Python) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/api/utils.md Demonstrates how to obtain a logger instance using `get_logger` from the `ontomem.utils.logging` module and log an informational message. This is useful for tracking application events and debugging. ```python from ontomem.utils.logging import get_logger logger = get_logger(__name__) logger.info("Memory operation completed") ``` -------------------------------- ### Install Optional Dependencies for GPU-Accelerated FAISS Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/installation.md Installs the CUDA-enabled version of FAISS for GPU acceleration in vector search. This requires an NVIDIA GPU and is an optional dependency for performance-critical applications. ```bash pip install faiss-gpu ``` -------------------------------- ### Get OntoMem Version Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/api/overview.md Shows how to check the installed version of the OntoMem library using the `__version__` attribute. ```python import ontomem print(ontomem.__version__) # e.g., "0.1.3" ``` -------------------------------- ### Set OpenAI API Key (Python) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/installation.md Sets the OpenAI API key within a Python script by modifying the environment variables. This is an alternative to setting it globally in the shell, useful for specific application contexts. ```python import os os.environ["OPENAI_API_KEY"] = "your-api-key-here" ``` -------------------------------- ### Set OpenAI API Key (Environment Variable) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/installation.md Sets the OpenAI API key as an environment variable, which is necessary for utilizing LLM features in OntoMem. This is a common method for managing API keys securely. ```bash export OPENAI_API_KEY="your-api-key-here" ``` -------------------------------- ### Add Researcher Data to OntoMem Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/quick-start.md Adds researcher profile data to the OntoMem instance using the `add` method. Each call creates or updates a record based on the defined schema and key extractor. ```python # Add researcher profiles memory.add(ResearcherProfile( name="Yann LeCun", affiliation="Meta AI", research_interests=["deep learning", "convolutional networks"], publications=["Backpropagation Applied to Handwritten Zip Code Recognition"] )) memory.add(ResearcherProfile( name="Yoshua Bengio", affiliation="Mila", research_interests=["deep learning", "AI safety"], publications=["Learning Representations by Back-propagating Errors"] )) ``` -------------------------------- ### Initialize OntoMem with LLM and Pydantic Schema Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/index.md This example demonstrates how to initialize OntoMem with a custom Pydantic schema, a key extractor function, an LLM client, an embedder, and a specific merge strategy. It shows adding structured data to the memory. ```python from ontomem import OMem, MergeStrategy from pydantic import BaseModel from langchain_openai import ChatOpenAI, OpenAIEmbeddings # Define your schema class BugFixExperience(BaseModel): error_signature: str solutions: list[str] prevention_tips: str # Initialize memory memory = OMem( memory_schema=BugFixExperience, key_extractor=lambda x: x.error_signature, llm_client=ChatOpenAI(model="gpt-4o"), embedder=OpenAIEmbeddings(), strategy_or_merger=MergeStrategy.LLM.BALANCED ) # Add experiences memory.add(BugFixExperience( error_signature="ModuleNotFoundError: pandas", solutions=["pip install pandas"], prevention_tips="Check requirements.txt" )) ``` -------------------------------- ### Run Tests (Bash) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/faq.md Command to synchronize development dependencies and run the test suite for the OntoMem project. ```bash uv sync --group dev pytest tests/ ``` -------------------------------- ### Define Researcher Profile Schema with Pydantic Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/quick-start.md Defines a Pydantic BaseModel for a researcher's profile, including name, affiliation, research interests, publications, and an optional last updated timestamp. This schema serves as the structure for the memory system. ```python from pydantic import BaseModel from typing import List, Optional from datetime import datetime class ResearcherProfile(BaseModel): """A researcher's profile in your memory system.""" name: str # Will be the key affiliation: str research_interests: List[str] publications: List[str] last_updated: Optional[datetime] = None ``` -------------------------------- ### Initialize and Use OMem Core Memory Store with LLM Merging Source: https://context7.com/yifanfeng97/ontomem/llms.txt Demonstrates initializing the OMem core memory store with a Pydantic schema, a key extractor, LLM client, embedder, and an LLM-based merge strategy. It shows how to add items, which are automatically deduplicated and merged, and how to retrieve, inspect, and manage memory contents. ```python from pydantic import BaseModel from ontomem import OMem, MergeStrategy from langchain_openai import ChatOpenAI, OpenAIEmbeddings # Define your memory schema class UserProfile(BaseModel): uid: str name: str | None = None email: str | None = None skills: list[str] = [] # Initialize memory store with LLM-powered merging memory = OMem( memory_schema=UserProfile, key_extractor=lambda x: x.uid, # Function to extract unique ID llm_client=ChatOpenAI(model="gpt-4o"), embedder=OpenAIEmbeddings(), strategy_or_merger=MergeStrategy.LLM.BALANCED, max_workers=3 # Control LLM concurrency to prevent rate limits ) # Add items - duplicates are automatically merged memory.add(UserProfile(uid="u1", name="Alice", skills=["Python"])) memory.add(UserProfile(uid="u1", email="alice@example.com", skills=["Docker"])) # Retrieve consolidated record alice = memory.get("u1") print(alice.name) # "Alice" print(alice.email) # "alice@example.com" print(alice.skills) # ["Python", "Docker"] - merged! # Properties print(memory.size) # 1 (deduplicated) print(memory.keys) # ["u1"] print(memory.items) # [UserProfile(uid="u1", ...)] # Remove item memory.remove("u1") # Returns True if found memory.clear() # Wipe all memory ``` -------------------------------- ### Initialize OntoMem with Pydantic Schema and LLM Source: https://github.com/yifanfeng97/ontomem/blob/main/README.md Demonstrates how to define a memory schema using Pydantic and initialize the OntoMem client. It includes setting up LLM clients for merging and embeddings, and configuring concurrency for rate limit prevention. ```python from pydantic import BaseModel from ontomem import OMem from langchain_openai import ChatOpenAI, OpenAIEmbeddings # 1. Define your memory schema class UserProfile(BaseModel): name: str skills: list[str] last_seen: str # 2. Initialize with LLM merging and concurrency control (v0.1.5+) memory = OMem( memory_schema=UserProfile, key_extractor=lambda x: x.name, llm_client=ChatOpenAI(model="gpt-4o"), embedder=OpenAIEmbeddings(), max_workers=3 # 🆕 Control LLM batch concurrency to prevent rate limits ) ``` -------------------------------- ### Python Data Structures for OMem Examples Source: https://github.com/yifanfeng97/ontomem/blob/main/examples/EXAMPLES.md Defines the data structures used in various OMem examples, outlining the fields and their types for each memory type. These structures are fundamental for organizing and storing information within the OMem framework. ```python error_id: str # Unique error identifier error_type: str # Type of error error_message: str # Error message stack_trace: str | None # Stack trace solutions: list[str] # Multiple solutions found attempted_fixes: list[str] # Fixes tried so far root_cause: str | None # Inferred root cause ``` ```python player_id: str # Player unique ID player_name: str | None # Known player names titles_earned: list[str] # Achievements reputation_events: list[str] # Important events known_skills: list[str] # Discovered skills trade_history: list[dict] # Transaction history first_meeting_location: str | None # First encounter place last_known_location: str | None # Last seen location npc_opinion: str | None # NPC's opinion of player party_relationship: str | None # Relationship status ``` ```python paper_id: str # Paper unique ID title: str # Paper title authors: list[str] # Author names abstract: str # Paper abstract year: int # Publication year citations: int # Citation count keywords: list[str] # Research keywords related_papers: list[str] # Related paper IDs ``` ```python customer_id: str # Customer ID name: str | None # Customer name email: str | None # Email address phone: str | None # Phone number company: str | None # Company/Organization job_title: str | None # Job title total_spending: float | None # Lifetime spending support_tickets: list[str] # Support ticket IDs preferred_products: list[str] # Product preferences communication_preferences: list # Preferred channels data_sources: list[str] # Which systems provided data last_updated: str | None # Last update timestamp ``` ```python session_id: str # Conversation session ID user_name: str | None # User's name known_topics: list[str] # Discussed topics user_preferences: list[str] # Stated preferences user_interests: list[str] # Inferred interests goals_discussed: list[str] # User's goals decisions_made: list[str] # Agreed decisions open_questions: list[str] # Unanswered questions context_notes: str | None # Additional context ``` -------------------------------- ### Select Embeddings Model (Python) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/faq.md Demonstrates how to initialize popular embeddings models using Langchain. Includes options for OpenAI embeddings and open-source HuggingFace embeddings. ```python from langchain_openai import OpenAIEmbeddings embedder = OpenAIEmbeddings(model="text-embedding-3-small") ``` ```python from langchain_community.embeddings import HuggingFaceEmbeddings embedder = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2") ``` -------------------------------- ### Temporal Memory and Daily Consolidation with Composite Keys in OntoMem Source: https://github.com/yifanfeng97/ontomem/blob/main/README.md Shows how to implement temporal memory and daily consolidation using composite keys in OntoMem. This example uses a `DailyTrace` schema where events occurring on the same day for the same user are merged into a single record, accumulating actions and synthesizing a daily summary. ```python from ontomem import OMem, MergeStrategy class DailyTrace(BaseModel): user: str date: str actions: list[str] # Accumulates all day summary: str # LLM synthesizes entire day memory = OMem( memory_schema=DailyTrace, key_extractor=lambda x: f"{x.user}_{x.date}", # <-- THE MAGIC KEY llm_client=ChatOpenAI(model="gpt-4o"), embedder=OpenAIEmbeddings(), strategy_or_merger=MergeStrategy.LLM.BALANCED ) # 9:00 AM event memory.add(DailyTrace(user="Alice", date="2024-01-01", actions=["Login"])) # 5:00 PM event (Same day → Merges into SAME record) memory.add(DailyTrace(user="Alice", date="2024-01-01", actions=["Logout"])) ``` -------------------------------- ### OMem Constructor and Core Methods Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/api/overview.md Demonstrates the initialization of the OMem class and its fundamental methods for managing memory entities. This includes adding, getting, removing, clearing, building indexes, searching, and dumping/loading memory states. It highlights the use of Pydantic models, key extractors, and optional LLM/embedding clients. ```python from ontomem import OMem, MergeStrategy from typing import Type, Callable, Any, Optional from langchain_core.language_models import BaseChatModel from langchain_core.embeddings import Embeddings # Assuming T, LLMClient, Embeddings, and MergeStrategy are defined elsewhere # Constructor Example # memory = OMem( # memory_schema=YourPydanticModel, # key_extractor=lambda x: x.id, # Function to extract unique key # llm_client=Optional[BaseChatModel] = None, # embedder=Optional[Embeddings] = None, # merge_strategy: MergeStrategy = MergeStrategy.MERGE_FIELD # ) # Core Methods Examples # memory.add(entity) # Add a single item # memory.add([entity1, entity2]) # Add multiple items # entity = memory.get("unique_key") # success = memory.remove("unique_key") # memory.clear() # memory.build_index() # memory.build_index(force=True) # results = memory.search("query", top_k=5) # memory.dump("./memory_folder") # memory.load("./memory_folder") ``` -------------------------------- ### Semantic Search with Vector Index in Python Source: https://context7.com/yifanfeng97/ontomem/llms.txt This example demonstrates setting up Ontomem for semantic search by building a vector index. It uses `OpenAIEmbeddings` to embed specified fields (`title`, `abstract`) of `ResearchPaper` objects. The `build_index()` method prepares the index for efficient similarity searches based on natural language queries. ```python from pydantic import BaseModel from ontomem import OMem, MergeStrategy from langchain_openai import OpenAIEmbeddings class ResearchPaper(BaseModel): paper_id: str title: str authors: list[str] abstract: str year: int keywords: list[str] = [] memory = OMem( memory_schema=ResearchPaper, key_extractor=lambda x: x.paper_id, llm_client=None, embedder=OpenAIEmbeddings(model="text-embedding-3-small"), strategy_or_merger=MergeStrategy.MERGE_FIELD, fields_for_index=["title", "abstract"] ) memory.add([ ResearchPaper( paper_id="nlp_001", title="Attention Is All You Need", authors=["Vaswani, A."], abstract="We propose a new architecture based solely on attention mechanisms...", year=2017, keywords=["transformer", "attention"] ), ResearchPaper( paper_id="cv_001", title="Vision Transformer", authors=["Dosovitskiy, A."], abstract="A pure transformer applied directly to sequences of image patches...", year=2020, keywords=["vision", "transformer"] ) ]) memory.build_index() results = memory.search("transformer neural networks for images", top_k=2) for paper in results: print(f"- {paper.title}: {paper.abstract[:50]}...") ``` -------------------------------- ### Run Tests (Bash) Source: https://github.com/yifanfeng97/ontomem/blob/main/docs/en/contributing.md This snippet demonstrates how to execute tests for the OntoMem project using `pytest`. It includes options for running all tests, specific files, and tests with coverage. ```bash # Run all tests pytest tests/ # Run specific test file pytest tests/test_core.py # Run with coverage pytest --cov=ontomem tests/ ``` -------------------------------- ### Configure OntoMem with LLM Balanced Merge Strategy Source: https://github.com/yifanfeng97/ontomem/blob/main/README.md Initializes OntoMem with a specific schema and LLM client, setting the merge strategy to LLM.BALANCED. This strategy uses an LLM to intelligently merge conflicting data. ```python # Example: LLM intelligently merges conflicting information memory = OMem( ..., strategy_or_merger=MergeStrategy.LLM.BALANCED # or LLM.PREFER_INCOMING, LLM.PREFER_EXISTING, LLM.CUSTOM_RULE ) ```