ontomem 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. ontomem-0.1.0/.env.example +6 -0
  2. ontomem-0.1.0/.gitignore +216 -0
  3. ontomem-0.1.0/PKG-INFO +362 -0
  4. ontomem-0.1.0/README.md +332 -0
  5. ontomem-0.1.0/README_ZH.md +333 -0
  6. ontomem-0.1.0/examples/01_self_improving_debugger.py +201 -0
  7. ontomem-0.1.0/examples/02_rpg_npc_memory.py +185 -0
  8. ontomem-0.1.0/examples/03_semantic_scholar.py +285 -0
  9. ontomem-0.1.0/examples/04_multi_source_fusion.py +276 -0
  10. ontomem-0.1.0/examples/05_conversation_history.py +260 -0
  11. ontomem-0.1.0/examples/EXAMPLES.md +179 -0
  12. ontomem-0.1.0/examples/README.md +199 -0
  13. ontomem-0.1.0/examples/zh/01_self_improving_debugger.py +199 -0
  14. ontomem-0.1.0/examples/zh/02_rpg_npc_memory.py +184 -0
  15. ontomem-0.1.0/examples/zh/03_semantic_scholar.py +285 -0
  16. ontomem-0.1.0/examples/zh/04_multi_source_fusion.py +276 -0
  17. ontomem-0.1.0/examples/zh/05_conversation_history.py +259 -0
  18. ontomem-0.1.0/examples/zh/README.md +138 -0
  19. ontomem-0.1.0/ontomem/__init__.py +43 -0
  20. ontomem-0.1.0/ontomem/core/__init__.py +5 -0
  21. ontomem-0.1.0/ontomem/core/base.py +86 -0
  22. ontomem-0.1.0/ontomem/core/omem.py +459 -0
  23. ontomem-0.1.0/ontomem/merger/__init__.py +156 -0
  24. ontomem-0.1.0/ontomem/merger/base.py +318 -0
  25. ontomem-0.1.0/ontomem/merger/classic_merger/__init__.py +11 -0
  26. ontomem-0.1.0/ontomem/merger/classic_merger/keep_new.py +34 -0
  27. ontomem-0.1.0/ontomem/merger/classic_merger/keep_old.py +34 -0
  28. ontomem-0.1.0/ontomem/merger/classic_merger/merge_field.py +82 -0
  29. ontomem-0.1.0/ontomem/merger/llm_merger/__init__.py +13 -0
  30. ontomem-0.1.0/ontomem/merger/llm_merger/balanced_merge.py +87 -0
  31. ontomem-0.1.0/ontomem/merger/llm_merger/base.py +146 -0
  32. ontomem-0.1.0/ontomem/merger/llm_merger/existing_first.py +86 -0
  33. ontomem-0.1.0/ontomem/merger/llm_merger/incoming_first.py +86 -0
  34. ontomem-0.1.0/ontomem/utils/__init__.py +5 -0
  35. ontomem-0.1.0/ontomem/utils/logging.py +54 -0
  36. ontomem-0.1.0/pyproject.toml +45 -0
  37. ontomem-0.1.0/tests/__init__.py +1 -0
  38. ontomem-0.1.0/tests/conftest.py +68 -0
  39. ontomem-0.1.0/tests/fixtures/__init__.py +1 -0
  40. ontomem-0.1.0/tests/fixtures/sample_schemas.py +31 -0
  41. ontomem-0.1.0/tests/integration/__init__.py +1 -0
  42. ontomem-0.1.0/tests/integration/test_end_to_end.py +201 -0
  43. ontomem-0.1.0/tests/unit/__init__.py +1 -0
  44. ontomem-0.1.0/tests/unit/test_omem_core.py +142 -0
  45. ontomem-0.1.0/tests/unit/test_omem_merge.py +158 -0
  46. ontomem-0.1.0/tests/unit/test_omem_persistence.py +155 -0
  47. ontomem-0.1.0/tests/unit/test_omem_search.py +178 -0
  48. ontomem-0.1.0/uv.lock +2538 -0
@@ -0,0 +1,6 @@
1
+ # Ontomem Configuration
2
+ # Copy this file to .env and fill in your actual values
3
+
4
+ # OpenAI API Key (Required for LLM and embeddings tests)
5
+ # Get your API key from: https://platform.openai.com/api-keys
6
+ OPENAI_API_KEY=sk-...
@@ -0,0 +1,216 @@
1
+ # Project specific
2
+ temp/
3
+
4
+ # Byte-compiled / optimized / DLL files
5
+ __pycache__/
6
+ *.py[cod]
7
+ *$py.class
8
+ *.so
9
+
10
+ # C extensions
11
+ *.o
12
+
13
+ # Distribution / packaging
14
+ .Python
15
+ build/
16
+ develop-eggs/
17
+ dist/
18
+ downloads/
19
+ eggs/
20
+ .eggs/
21
+ lib/
22
+ lib64/
23
+ parts/
24
+ sdist/
25
+ var/
26
+ wheels/
27
+ share/python-wheels/
28
+ *.egg-info/
29
+ .installed.cfg
30
+ *.egg
31
+ MANIFEST
32
+
33
+ # PyInstaller
34
+ # Usually these files are written by a python script from a template
35
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
36
+ *.manifest
37
+ *.spec
38
+
39
+ # Installer logs
40
+ pip-log.txt
41
+ pip-delete-this-directory.txt
42
+
43
+ # Unit test / coverage reports
44
+ htmlcov/
45
+ .tox/
46
+ .nox/
47
+ .coverage
48
+ .coverage.*
49
+ .cache
50
+ nosetests.xml
51
+ coverage.xml
52
+ *.cover
53
+ *.py,cover
54
+ .hypothesis/
55
+ .pytest_cache/
56
+
57
+ # Translations
58
+ *.mo
59
+ *.pot
60
+
61
+ # Django stuff:
62
+ *.log
63
+ local_settings.py
64
+ db.sqlite3
65
+ db.sqlite3-journal
66
+
67
+ # Flask stuff:
68
+ instance/
69
+ .webassets-cache
70
+
71
+ # Scrapy stuff:
72
+ .scrapy
73
+
74
+ # Sphinx documentation docs/
75
+ docs/_build/
76
+
77
+ # PyBuilder
78
+ .pybuilder/
79
+ target/
80
+
81
+ # Jupyter Notebook
82
+ .ipynb_checkpoints
83
+
84
+ # IPython
85
+ profile_default/
86
+ ipython_config.py
87
+
88
+ # pyenv
89
+ # For a library or package, you might want to ignore these files since the code is
90
+ # intended to run in multiple environments; otherwise, check them in:
91
+ .python-version
92
+
93
+ # pipenv
94
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
95
+ # However, in some cases (e.g. if pipenv is installed locally), it may be better to exclude it:
96
+ #Pipfile.lock
97
+
98
+ # poetry
99
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
100
+ # This is especially recommended for binary packages to ensure reproducibility and quick releases.
101
+ # However, it may be better to exclude it for libraries or packages intended to be published to
102
+ # PyPI or conda-forge, to avoid pinning dependencies too strongly.
103
+ #poetry.lock
104
+ #poetry.toml
105
+ #.python-version
106
+
107
+ # pdm
108
+ # Similar to poetry, PDM makes lockfiles optional.
109
+ #pdm.lock
110
+ #pdm.toml
111
+ #.pdm-python
112
+
113
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
114
+ __pypackages__/
115
+
116
+ # Celery stuff
117
+ celerybeat-schedule
118
+ celerybeat.pid
119
+
120
+ # SageMath parsed files
121
+ *.sage.py
122
+
123
+ # Environments
124
+ .env
125
+ .venv
126
+ env/
127
+ venv/
128
+ ENV/
129
+ env.bak/
130
+ venv.bak/
131
+
132
+ # Spyder project settings
133
+ .spyderproject
134
+ .spyproject
135
+
136
+ # Rope project settings
137
+ .ropeproject
138
+
139
+ # mkdocs documentation
140
+ /site
141
+
142
+ # mypy
143
+ .mypy_cache/
144
+ .dmypy.json
145
+ dmypy.json
146
+
147
+ # Pyre type checker
148
+ .pyre/
149
+
150
+ # IDE
151
+ .vscode/
152
+ .idea/
153
+
154
+ # OS generated files
155
+ .DS_Store
156
+ .DS_Store?
157
+ ._*
158
+ .Spotlight-V100
159
+ .Trashes
160
+ ehthumbs.db
161
+ Thumbs.db
162
+
163
+ # Temporary files
164
+ *.tmp
165
+ *.temp
166
+
167
+ # Environment variable configuration
168
+ .envrc
169
+ .direnv/
170
+
171
+ # Coverage
172
+ .coverage*
173
+ coverage.xml
174
+ htmlcov/
175
+
176
+ # Logs
177
+ logs/
178
+ *.log
179
+
180
+ # Runtime
181
+ .pyc
182
+ .pyo
183
+ *~
184
+ ~*
185
+
186
+ # Git
187
+ *.orig
188
+ *.rej
189
+
190
+ # Vim
191
+ *.un~
192
+ Session.vim
193
+
194
+ # Emacs
195
+ *~
196
+ \#*\#
197
+ /.emacs.desktop
198
+ /.emacs.desktop.lock
199
+ *.elc
200
+ auto-save-list
201
+ tramp
202
+ .\#*
203
+
204
+ # Intellij
205
+ *.iml
206
+ *.iws
207
+ *.ipr
208
+
209
+ # Visual Studio Code
210
+ .vscode/
211
+
212
+ # Generated files
213
+ /requirements.txt
214
+
215
+ # Python virtual environments
216
+ venv/
ontomem-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,362 @@
1
+ Metadata-Version: 2.4
2
+ Name: ontomem
3
+ Version: 0.1.0
4
+ Summary: A self-consolidating memory layer for AI agents with schema-first design, intelligent merging, and hybrid search capabilities
5
+ Author-email: yifanfeng97 <evanfeng97@gmail.com>
6
+ License: MIT
7
+ Keywords: ai-agent,knowledge-graph,llm,memory,pydantic,rag,semantic-search
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Requires-Python: >=3.11
17
+ Requires-Dist: faiss-cpu>=1.13.2
18
+ Requires-Dist: langchain-community>=0.4.1
19
+ Requires-Dist: langchain-openai>=1.1.6
20
+ Requires-Dist: langchain>=1.2.1
21
+ Requires-Dist: loguru>=0.7.3
22
+ Requires-Dist: pydantic>=2.12.5
23
+ Requires-Dist: python-dotenv>=1.2.1
24
+ Provides-Extra: dev
25
+ Requires-Dist: mkdocs-material>=9.7.1; extra == 'dev'
26
+ Requires-Dist: mkdocs>=1.6.1; extra == 'dev'
27
+ Requires-Dist: mkdocstrings[python]>=1.0.0; extra == 'dev'
28
+ Requires-Dist: pytest>=9.0.2; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # 🧠 Ontomem: The Self-Consolidating Memory Layer
32
+
33
+ [δΈ­ζ–‡η‰ˆζœ¬](README_ZH.md) | English
34
+
35
+ > **Give your AI agent a "coherent" memory, not just "fragmented" retrieval.**
36
+
37
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](https://www.python.org/)
38
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
39
+
40
+ Traditional RAG (Retrieval-Augmented Generation) systems retrieve text fragments. **Ontomem** maintains **structured entities** using Pydantic schemas and intelligent merging algorithms. It automatically consolidates fragmented observations into complete knowledge graph nodes.
41
+
42
+ **It doesn't just store dataβ€”it continuously "digests" and "organizes" it.**
43
+
44
+ ---
45
+
46
+ ## ✨ Why Ontomem?
47
+
48
+ ### 🧩 Schema-First & Type-Safe
49
+ Built on **Pydantic**. All memories are strongly-typed objects. Say goodbye to `{"unknown": "dict"}` hell and embrace IDE autocomplete and type checking.
50
+
51
+ ### πŸ”„ Auto-Consolidation
52
+ When you insert different pieces of information about the same entity (same ID) multiple times, Ontomem doesn't create duplicates. It intelligently merges them into a **Golden Record** using configurable strategies (field overrides, list merging, or **LLM-powered intelligent fusion**).
53
+
54
+ ### πŸ” Hybrid Search
55
+ - **Key-Value Lookup**: O(1) exact entity access
56
+ - **Vector Search**: Built-in FAISS indexing for semantic similarity search, automatically synced
57
+
58
+ ### πŸ’Ύ Stateful & Persistent
59
+ Save your complete memory state (structured data + vector indices) to disk and restore it in seconds on next startup.
60
+
61
+ ---
62
+
63
+ ## πŸš€ Quick Start: Building a "Self-Improving" Experience Library
64
+
65
+ Imagine an AI coding agent that debugs issues. Without memory, it repeats the same trial-and-error process every time. With **Ontomem**, it builds a persistent **"Debugging Playbook"** that evolves with each new problem encountered.
66
+
67
+ ### 1. Define Your Experience Schema
68
+
69
+ ```python
70
+ from pydantic import BaseModel
71
+ from typing import List, Optional
72
+
73
+ class BugFixExperience(BaseModel):
74
+ """A living record of debugging knowledge."""
75
+ error_signature: str # Key: e.g., "ModuleNotFoundError: pandas"
76
+ root_causes: List[str] # Different reasons this error can occur
77
+ solutions: List[str] # Multiple working solutions discovered
78
+ prevention_tips: str # Synthesized understanding of how to avoid it
79
+ last_updated: Optional[str] = None
80
+ ```
81
+
82
+ ### 2. Initialize with LLM-Powered Merging
83
+
84
+ We use the `LLM.BALANCED` strategy so Ontomem doesn't just list solutionsβ€”it **synthesizes** them into coherent, actionable guidance.
85
+
86
+ ```python
87
+ from ontomem import OMem, MergeStrategy
88
+ from langchain_openai import ChatOpenAI, OpenAIEmbeddings
89
+
90
+ experience_memory = OMem(
91
+ memory_schema=BugFixExperience,
92
+ key_extractor=lambda x: x.error_signature,
93
+ llm_client=ChatOpenAI(model="gpt-4o"),
94
+ embedder=OpenAIEmbeddings(),
95
+ merge_strategy=MergeStrategy.LLM.BALANCED
96
+ )
97
+ ```
98
+
99
+ ### 3. The Agent Learns Over Time
100
+
101
+ #### Day 1: The First Encounter
102
+ The agent encounters `ModuleNotFoundError` for pandas and fixes it with `pip install`.
103
+
104
+ ```python
105
+ # Experience 1: Initial observation
106
+ experience_memory.add(BugFixExperience(
107
+ error_signature="ModuleNotFoundError: No module named 'pandas'",
108
+ root_causes=["Missing library in environment"],
109
+ solutions=["Run: pip install pandas"],
110
+ prevention_tips="Always check requirements.txt before running code."
111
+ ))
112
+ ```
113
+
114
+ #### Day 2: New Context, Different Fix
115
+ The agent encounters the same error in a Docker container where pip fails, but `apt-get install python3-pandas` works.
116
+
117
+ ```python
118
+ # Experience 2: Different context, same error
119
+ experience_memory.add(BugFixExperience(
120
+ error_signature="ModuleNotFoundError: No module named 'pandas'",
121
+ root_causes=["Package not in system Python", "Binary incompatibility with pip"],
122
+ solutions=["Run: apt-get install python3-pandas", "Use system package manager in containers"],
123
+ prevention_tips="In containerized environments, prefer system packages for compiled dependencies."
124
+ ))
125
+ ```
126
+
127
+ #### Day 3: Agent Seeks Wisdom
128
+ When a new agent instance encounters the same error, it queries the evolved knowledge base:
129
+
130
+ ```python
131
+ # Retrieve consolidated wisdom
132
+ guidance = experience_memory.get("ModuleNotFoundError: No module named 'pandas'")
133
+
134
+ print("Root Causes:")
135
+ for cause in guidance.root_causes:
136
+ print(f" - {cause}")
137
+ # Output:
138
+ # - Missing library in environment
139
+ # - Package not in system Python
140
+ # - Binary incompatibility with pip
141
+
142
+ print("\nSolutions:")
143
+ for i, solution in enumerate(guidance.solutions, 1):
144
+ print(f" {i}. {solution}")
145
+ # Output:
146
+ # 1. Run: pip install pandas (standard approach)
147
+ # 2. Run: apt-get install python3-pandas (for system Python)
148
+ # 3. Use system package manager in containers
149
+
150
+ print("\nPrevention Tips:")
151
+ print(guidance.prevention_tips)
152
+ # Output: "Check requirements.txt before running code.
153
+ # In containers, prefer system packages for compiled dependencies.
154
+ # Consider using virtual environments to isolate dependencies."
155
+ ```
156
+
157
+ #### Day 4: Semantic Search for Similar Problems
158
+ The agent doesn't remember the exact error, but can search by concept:
159
+
160
+ ```python
161
+ # Semantic search: Find solutions for import-related issues
162
+ similar_issues = experience_memory.search(
163
+ "Python module import failures dependency missing",
164
+ k=5
165
+ )
166
+
167
+ print(f"Found {len(similar_issues)} related debugging experiences")
168
+ ```
169
+
170
+ **The agent went from "trial and error" to "informed decision-making". No boilerplate. No manual consolidation. Just add experiences and let Ontomem synthesize wisdom.**
171
+
172
+ ---
173
+
174
+ ## πŸ” Semantic Search
175
+
176
+ Build an index and search by natural language:
177
+
178
+ ```python
179
+ # Build vector index
180
+ memory.build_index()
181
+
182
+ # Semantic search
183
+ results = memory.search("Find researchers working on transformer models and attention mechanisms")
184
+
185
+ for researcher in results:
186
+ print(f"- {researcher.name}: {researcher.research_interests}")
187
+ ```
188
+
189
+ ---
190
+
191
+ ## πŸ› οΈ Merge Strategies
192
+
193
+ Choose how to handle conflicts:
194
+
195
+ | Strategy | Behavior | Use Case |
196
+ |----------|----------|----------|
197
+ | `FIELD_MERGE` | Non-null overwrites, lists append | Simple attribute collection |
198
+ | `KEEP_NEW` | Latest data wins | Status updates (current role, last seen) |
199
+ | `KEEP_OLD` | First observation stays | Historical records (first publication year) |
200
+ | `LLM.BALANCED` | **LLM-driven semantic merging** | Complex synthesis, contradiction resolution |
201
+
202
+ ```python
203
+ # Example: LLM intelligently merges conflicting bios
204
+ memory = OMem(
205
+ ...,
206
+ merge_strategy=MergeStrategy.LLM.BALANCED
207
+ )
208
+ ```
209
+
210
+ ---
211
+
212
+ ## πŸ’Ύ Save & Load
213
+
214
+ Snapshot your entire memory state:
215
+
216
+ ```python
217
+ # Save (structured data β†’ memory.json, vectors β†’ FAISS indices)
218
+ memory.dump("./researcher_knowledge")
219
+
220
+ # Later, restore instantly
221
+ new_memory = OMem(...)
222
+ new_memory.load("./researcher_knowledge")
223
+ ```
224
+
225
+ ---
226
+
227
+ ## πŸ“Š Ontomem vs Traditional Approaches
228
+
229
+ | Feature | Traditional Vector DB | Ontomem 🧠 |
230
+ |---------|----------------------|-----------|
231
+ | **Storage Unit** | Text chunks | **Structured Objects** |
232
+ | **Deduplication** | Manual or via embeddings | **Native, ID-based** |
233
+ | **Updates** | Append-only (creates dupes) | **Auto-merge (upsert)** |
234
+ | **Query Results** | Similar text fragments | **Complete entities** |
235
+ | **Type Safety** | ❌ None | βœ… **Pydantic** |
236
+ | **Indexing** | Manual sync needed | βœ… **Auto-synced** |
237
+
238
+ ---
239
+
240
+ ## 🎯 Use Cases
241
+
242
+ ### πŸ€– AI Research Assistant
243
+ Consolidate researcher profiles, papers, and citations from multiple sources.
244
+
245
+ ### πŸ‘€ Personal Knowledge Graph
246
+ Build a living profile of contacts, their preferences, skills, and interaction history from conversations.
247
+
248
+ ### 🏒 Enterprise Data Hub
249
+ Unify customer/employee records from CRM, email, support tickets, and social media.
250
+
251
+ ### 🧠 AI Agent Long-Term Memory
252
+ An autonomous agent accumulates experiences and observationsβ€”Ontomem keeps them organized and searchable.
253
+
254
+ ---
255
+
256
+ ## πŸ”§ Installation
257
+
258
+ ```bash
259
+ pip install ontomem
260
+ ```
261
+
262
+ Or with `uv`:
263
+ ```bash
264
+ uv add ontomem
265
+ ```
266
+
267
+ **Requirements:**
268
+ - Python 3.11+
269
+ - LangChain (for LLM integration)
270
+ - Pydantic (for schema definition)
271
+ - FAISS (for vector search)
272
+
273
+ ---
274
+
275
+ ## πŸ“š API Reference
276
+
277
+ ### Core Methods
278
+
279
+ #### `add(items: Union[T, List[T]]) β†’ None`
280
+ Add item(s) to memory. Automatically merges duplicates by key.
281
+
282
+ ```python
283
+ memory.add(ResearcherProfile(...))
284
+ memory.add([item1, item2, item3])
285
+ ```
286
+
287
+ #### `get(key: Any) β†’ Optional[T]`
288
+ Retrieve an entity by its unique key.
289
+
290
+ ```python
291
+ researcher = memory.get("yann_lecun_001")
292
+ ```
293
+
294
+ #### `build_index(force: bool = False) β†’ None`
295
+ Build or rebuild the vector index for semantic search.
296
+
297
+ ```python
298
+ memory.build_index() # Build if clean
299
+ memory.build_index(force=True) # Force rebuild
300
+ ```
301
+
302
+ #### `search(query: str, k: int = 5) β†’ List[T]`
303
+ Semantic search over all entities.
304
+
305
+ ```python
306
+ results = memory.search("transformers and attention", k=10)
307
+ ```
308
+
309
+ #### `dump(folder_path: Union[str, Path]) β†’ None`
310
+ Save memory state (data + index) to disk.
311
+
312
+ ```python
313
+ memory.dump("./my_memory")
314
+ ```
315
+
316
+ #### `load(folder_path: Union[str, Path]) β†’ None`
317
+ Load memory state from disk.
318
+
319
+ ```python
320
+ memory.load("./my_memory")
321
+ ```
322
+
323
+ #### `remove(key: Any) β†’ bool`
324
+ Remove an entity by key.
325
+
326
+ ```python
327
+ success = memory.remove("yann_lecun_001")
328
+ ```
329
+
330
+ #### `clear() β†’ None`
331
+ Clear all entities and indices.
332
+
333
+ ```python
334
+ memory.clear()
335
+ ```
336
+
337
+ ### Properties
338
+
339
+ #### `keys: List[Any]`
340
+ All unique keys in memory.
341
+
342
+ #### `items: List[T]`
343
+ All entity instances.
344
+
345
+ #### `size: int`
346
+ Number of entities.
347
+
348
+ ---
349
+
350
+ ## 🀝 Contributing
351
+
352
+ We're building the next generation of AI memory standards. PRs and issues welcome!
353
+
354
+ ---
355
+
356
+ ## πŸ“ License
357
+
358
+ MIT License - See LICENSE file for details.
359
+
360
+ ---
361
+
362
+ **Built with ❀️ for AI developers who believe memory is more than just search.**