noema-rag 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 (77) hide show
  1. noema_rag-0.1.0/.gitignore +10 -0
  2. noema_rag-0.1.0/LICENSE +201 -0
  3. noema_rag-0.1.0/PKG-INFO +152 -0
  4. noema_rag-0.1.0/README.md +108 -0
  5. noema_rag-0.1.0/benchmarks/__init__.py +5 -0
  6. noema_rag-0.1.0/benchmarks/baselines.py +171 -0
  7. noema_rag-0.1.0/benchmarks/dataset.py +165 -0
  8. noema_rag-0.1.0/benchmarks/metrics.py +91 -0
  9. noema_rag-0.1.0/benchmarks/report.py +107 -0
  10. noema_rag-0.1.0/benchmarks/run_benchmark.py +83 -0
  11. noema_rag-0.1.0/benchmarks/runner.py +144 -0
  12. noema_rag-0.1.0/pyproject.toml +135 -0
  13. noema_rag-0.1.0/src/noema/__init__.py +48 -0
  14. noema_rag-0.1.0/src/noema/canonicalize/__init__.py +5 -0
  15. noema_rag-0.1.0/src/noema/canonicalize/dedup.py +240 -0
  16. noema_rag-0.1.0/src/noema/cli/__init__.py +3 -0
  17. noema_rag-0.1.0/src/noema/cli/cli.py +201 -0
  18. noema_rag-0.1.0/src/noema/compress.py +116 -0
  19. noema_rag-0.1.0/src/noema/graph/__init__.py +5 -0
  20. noema_rag-0.1.0/src/noema/graph/builder.py +145 -0
  21. noema_rag-0.1.0/src/noema/integrations/__init__.py +22 -0
  22. noema_rag-0.1.0/src/noema/integrations/langchain.py +110 -0
  23. noema_rag-0.1.0/src/noema/integrations/llamaindex.py +106 -0
  24. noema_rag-0.1.0/src/noema/integrations/tokens.py +84 -0
  25. noema_rag-0.1.0/src/noema/notation/__init__.py +6 -0
  26. noema_rag-0.1.0/src/noema/notation/decoder.py +151 -0
  27. noema_rag-0.1.0/src/noema/notation/encoder.py +90 -0
  28. noema_rag-0.1.0/src/noema/parser/__init__.py +6 -0
  29. noema_rag-0.1.0/src/noema/parser/coref.py +81 -0
  30. noema_rag-0.1.0/src/noema/parser/entities.py +73 -0
  31. noema_rag-0.1.0/src/noema/parser/relations.py +184 -0
  32. noema_rag-0.1.0/src/noema/parser/transformer_relations.py +165 -0
  33. noema_rag-0.1.0/src/noema/retrieval/__init__.py +16 -0
  34. noema_rag-0.1.0/src/noema/retrieval/assemble.py +109 -0
  35. noema_rag-0.1.0/src/noema/retrieval/expand.py +101 -0
  36. noema_rag-0.1.0/src/noema/retrieval/vector_search.py +71 -0
  37. noema_rag-0.1.0/src/noema/schema.py +134 -0
  38. noema_rag-0.1.0/src/noema/storage/__init__.py +22 -0
  39. noema_rag-0.1.0/src/noema/storage/backends.py +110 -0
  40. noema_rag-0.1.0/src/noema/storage/bundle.py +220 -0
  41. noema_rag-0.1.0/src/noema/storage/knowledge_base.py +338 -0
  42. noema_rag-0.1.0/src/noema/storage/neo4j_backend.py +194 -0
  43. noema_rag-0.1.0/src/noema/storage/rdf_backend.py +207 -0
  44. noema_rag-0.1.0/src/noema/validator/__init__.py +5 -0
  45. noema_rag-0.1.0/src/noema/validator/nli.py +139 -0
  46. noema_rag-0.1.0/src/noema/validator/roundtrip.py +75 -0
  47. noema_rag-0.1.0/tests/integration/__init__.py +0 -0
  48. noema_rag-0.1.0/tests/unit/__init__.py +0 -0
  49. noema_rag-0.1.0/tests/unit/conftest.py +31 -0
  50. noema_rag-0.1.0/tests/unit/test_assemble.py +139 -0
  51. noema_rag-0.1.0/tests/unit/test_backends.py +168 -0
  52. noema_rag-0.1.0/tests/unit/test_baselines.py +184 -0
  53. noema_rag-0.1.0/tests/unit/test_benchmark_dataset.py +95 -0
  54. noema_rag-0.1.0/tests/unit/test_benchmark_report.py +160 -0
  55. noema_rag-0.1.0/tests/unit/test_benchmark_runner.py +156 -0
  56. noema_rag-0.1.0/tests/unit/test_bundle.py +205 -0
  57. noema_rag-0.1.0/tests/unit/test_canonicalize.py +392 -0
  58. noema_rag-0.1.0/tests/unit/test_cli.py +252 -0
  59. noema_rag-0.1.0/tests/unit/test_compress.py +202 -0
  60. noema_rag-0.1.0/tests/unit/test_coref.py +169 -0
  61. noema_rag-0.1.0/tests/unit/test_decoder.py +124 -0
  62. noema_rag-0.1.0/tests/unit/test_encoder.py +151 -0
  63. noema_rag-0.1.0/tests/unit/test_entities.py +63 -0
  64. noema_rag-0.1.0/tests/unit/test_expand.py +142 -0
  65. noema_rag-0.1.0/tests/unit/test_graph_builder.py +148 -0
  66. noema_rag-0.1.0/tests/unit/test_integrations.py +289 -0
  67. noema_rag-0.1.0/tests/unit/test_knowledge_base.py +378 -0
  68. noema_rag-0.1.0/tests/unit/test_knowledge_base_streaming.py +248 -0
  69. noema_rag-0.1.0/tests/unit/test_metrics.py +106 -0
  70. noema_rag-0.1.0/tests/unit/test_neo4j_backend.py +182 -0
  71. noema_rag-0.1.0/tests/unit/test_nli.py +130 -0
  72. noema_rag-0.1.0/tests/unit/test_rdf_backend.py +142 -0
  73. noema_rag-0.1.0/tests/unit/test_relations.py +137 -0
  74. noema_rag-0.1.0/tests/unit/test_roundtrip.py +104 -0
  75. noema_rag-0.1.0/tests/unit/test_schema.py +101 -0
  76. noema_rag-0.1.0/tests/unit/test_transformer_relations.py +187 -0
  77. noema_rag-0.1.0/tests/unit/test_vector_search.py +116 -0
@@ -0,0 +1,10 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,152 @@
1
+ Metadata-Version: 2.5
2
+ Name: noema-rag
3
+ Version: 0.1.0
4
+ Summary: Convert text into compact logical form for token-efficient RAG
5
+ Project-URL: Homepage, https://github.com/Asyncinnovator/Noema
6
+ Project-URL: Documentation, https://github.com/Asyncinnovator/Noema/wiki
7
+ Project-URL: Issues, https://github.com/Asyncinnovator/Noema/issues
8
+ Project-URL: Changelog, https://github.com/Asyncinnovator/Noema/releases
9
+ Author-email: Rishu <sheth.rishu50@gmail.com>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: graphrag,knowledge-graph,llm,nlp,prompt-compression,rag,retrieval-augmented-generation,token-reduction
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Classifier: Topic :: Text Processing :: Linguistic
19
+ Requires-Python: >=3.13
20
+ Requires-Dist: click>=8.0
21
+ Requires-Dist: faiss-cpu>=1.15.0
22
+ Requires-Dist: networkx>=3.6.1
23
+ Requires-Dist: pydantic>=2.13.4
24
+ Requires-Dist: rich>=15.0.0
25
+ Requires-Dist: sentence-transformers>=5.7.0
26
+ Requires-Dist: spacy>=3.8.14
27
+ Requires-Dist: tiktoken>=0.13.0
28
+ Requires-Dist: torch>=2.5.0
29
+ Requires-Dist: transformers<5.0,>=4.40
30
+ Requires-Dist: typer>=0.27.1
31
+ Provides-Extra: advanced-nlp
32
+ Requires-Dist: fastcoref>=2.1.6; extra == 'advanced-nlp'
33
+ Provides-Extra: anthropic
34
+ Requires-Dist: anthropic>=0.40.0; extra == 'anthropic'
35
+ Provides-Extra: langchain
36
+ Requires-Dist: langchain-core>=0.3.0; extra == 'langchain'
37
+ Provides-Extra: llamaindex
38
+ Requires-Dist: llama-index-core>=0.12.0; extra == 'llamaindex'
39
+ Provides-Extra: neo4j
40
+ Requires-Dist: neo4j>=5.26.0; extra == 'neo4j'
41
+ Provides-Extra: rdf
42
+ Requires-Dist: rdflib>=7.1.0; extra == 'rdf'
43
+ Description-Content-Type: text/markdown
44
+
45
+ <div align="center">
46
+
47
+ <img src="docs/logo-name.png" alt="Noema: Python library for knowledge graph RAG and LLM context compression" width="100%">
48
+
49
+ # Noema
50
+
51
+ ### Convert text into compact logical form: fewer tokens, no lost context, built for RAG
52
+
53
+ Noema is a Python library for **token-efficient RAG**. It turns documents into a deduplicated
54
+ **knowledge graph** and sends your LLM only the facts a question needs, in a compact notation.
55
+
56
+ [![PyPI version](https://img.shields.io/pypi/v/noema-rag)](https://pypi.org/project/noema-rag/)
57
+ [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-green.svg)](LICENSE)
58
+ [![Python 3.13+](https://img.shields.io/badge/python-3.13%2B-blue)](pyproject.toml)
59
+ [![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000)](https://github.com/astral-sh/ruff)
60
+
61
+ </div>
62
+
63
+ ---
64
+
65
+ ## What is Noema?
66
+
67
+ **Noema** is a Python library for knowledge graph construction, LLM context compression and
68
+ Retrieval-Augmented Generation (RAG). Instead of treating documents as flat strings, it parses
69
+ text into a structured logical form of **entities and relations**, and organizes that
70
+ structure into a canonical, deduplicated graph.
71
+
72
+ At query time, only the sub-graph relevant to the question is rendered as a short,
73
+ line-oriented notation and placed in the prompt. The same compact representation that reduces
74
+ token usage is also the retrieval layer, so **token savings and retrieval quality come from
75
+ one design** rather than two systems bolted together.
76
+
77
+ ```
78
+ Larry Page founded Google in 1998. Sundar Pichai is the CEO of Google.
79
+
80
+ becomes
81
+
82
+ #1 Larry Page :PERSON
83
+ #2 Google :ORG
84
+ #3 Sundar Pichai :PERSON
85
+ #1 -found-> #2
86
+ #3 -ceo_of-> #2
87
+ ```
88
+
89
+ A typical RAG pipeline stores and re-embeds raw text chunks. Noema stores canonical facts,
90
+ merges repeated mentions of the same fact into one node, and checks its compact notation by
91
+ decoding it back to natural language and scoring the result (round-trip validation).
92
+
93
+ ## Why Noema? How it differs from other approaches
94
+
95
+ | | Plain-text RAG (chunk and embed) | Text-only prompt compressors | Noema |
96
+ |---|---|---|---|
97
+ | What is stored | Raw text chunks | Nothing (stateless) | Canonical, deduplicated facts |
98
+ | Multi-hop questions | Weak | Not applicable | Graph traversal connects facts across documents |
99
+ | Same fact in many documents | Repeated in every retrieval | Not addressed | Merged into one node |
100
+ | Context sent per query | Whole chunks | The compressed prompt | Only the relevant sub-graph |
101
+ | Meaning-loss check | None | Text similarity | Round-trip validation with a confidence score |
102
+ | Adding documents | Re-chunk and re-embed | Not applicable | Merges into the existing graph |
103
+
104
+ ## Features
105
+
106
+ - **Text to semantic graph**: entity and relation extraction, with optional coreference resolution and transformer-based relations
107
+ - **Canonicalization and deduplication**: one canonical node per fact, across one document or many
108
+ - **Compact notation**: a low-token representation for LLM context injection, decodable back to natural language
109
+ - **Hybrid retrieval**: vector similarity search plus multi-hop graph traversal, under a `max_tokens` budget
110
+ - **Round-trip validation**: a confidence score for how much meaning the notation keeps
111
+ - **Incremental knowledge base**: new documents merge into the existing graph; save and load as a single `.noema` file
112
+ - **Streaming ingestion**: batched ingestion with checkpoints for large document sets
113
+ - **Persistent backends**: optional Neo4j and RDF stores for larger knowledge bases
114
+ - **Framework integrations**: LangChain and LlamaIndex retrievers, plus OpenAI and Anthropic token counting
115
+ - **Command-line tool**: `noema` for compression, graph building, querying and inspection
116
+ - **Benchmark suite**: reproducible comparison against plain-chunk RAG and full-context stuffing
117
+
118
+ ## Quick look
119
+
120
+ ```python
121
+ import noema
122
+
123
+ kb = noema.KnowledgeBase()
124
+ kb.ingest(documents)
125
+ context = kb.retrieve("Who is Google's CEO?", max_tokens=200)
126
+
127
+ prompt = f"{context.text}\n\nQuestion: Who is Google's CEO?"
128
+ ```
129
+
130
+ ## Use cases
131
+
132
+ - Cutting LLM token costs in RAG pipelines and long-context applications
133
+ - Multi-hop question answering over facts spread across several documents
134
+ - Building a lightweight knowledge graph from text without hand-written schemas
135
+ - Keeping a knowledge base up to date as new documents arrive
136
+
137
+ ## Documentation
138
+
139
+ Installation, usage guides, CLI and integration docs are on the project Wiki.
140
+
141
+ ## Project status
142
+
143
+ Noema is under active development. The core pipeline, storage, retrieval, integrations, CLI
144
+ and benchmark suite are implemented; the public API may still change before 1.0.
145
+
146
+ ## License
147
+
148
+ Noema is licensed under the [Apache License 2.0](LICENSE).
149
+
150
+ <sub>Keywords: RAG, retrieval-augmented generation, knowledge graph, GraphRAG, LLM context
151
+ compression, prompt compression, token reduction, semantic compression, entity and relation
152
+ extraction, multi-hop question answering, LangChain, LlamaIndex, Neo4j, RDF, Python.</sub>
@@ -0,0 +1,108 @@
1
+ <div align="center">
2
+
3
+ <img src="docs/logo-name.png" alt="Noema: Python library for knowledge graph RAG and LLM context compression" width="100%">
4
+
5
+ # Noema
6
+
7
+ ### Convert text into compact logical form: fewer tokens, no lost context, built for RAG
8
+
9
+ Noema is a Python library for **token-efficient RAG**. It turns documents into a deduplicated
10
+ **knowledge graph** and sends your LLM only the facts a question needs, in a compact notation.
11
+
12
+ [![PyPI version](https://img.shields.io/pypi/v/noema-rag)](https://pypi.org/project/noema-rag/)
13
+ [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-green.svg)](LICENSE)
14
+ [![Python 3.13+](https://img.shields.io/badge/python-3.13%2B-blue)](pyproject.toml)
15
+ [![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000)](https://github.com/astral-sh/ruff)
16
+
17
+ </div>
18
+
19
+ ---
20
+
21
+ ## What is Noema?
22
+
23
+ **Noema** is a Python library for knowledge graph construction, LLM context compression and
24
+ Retrieval-Augmented Generation (RAG). Instead of treating documents as flat strings, it parses
25
+ text into a structured logical form of **entities and relations**, and organizes that
26
+ structure into a canonical, deduplicated graph.
27
+
28
+ At query time, only the sub-graph relevant to the question is rendered as a short,
29
+ line-oriented notation and placed in the prompt. The same compact representation that reduces
30
+ token usage is also the retrieval layer, so **token savings and retrieval quality come from
31
+ one design** rather than two systems bolted together.
32
+
33
+ ```
34
+ Larry Page founded Google in 1998. Sundar Pichai is the CEO of Google.
35
+
36
+ becomes
37
+
38
+ #1 Larry Page :PERSON
39
+ #2 Google :ORG
40
+ #3 Sundar Pichai :PERSON
41
+ #1 -found-> #2
42
+ #3 -ceo_of-> #2
43
+ ```
44
+
45
+ A typical RAG pipeline stores and re-embeds raw text chunks. Noema stores canonical facts,
46
+ merges repeated mentions of the same fact into one node, and checks its compact notation by
47
+ decoding it back to natural language and scoring the result (round-trip validation).
48
+
49
+ ## Why Noema? How it differs from other approaches
50
+
51
+ | | Plain-text RAG (chunk and embed) | Text-only prompt compressors | Noema |
52
+ |---|---|---|---|
53
+ | What is stored | Raw text chunks | Nothing (stateless) | Canonical, deduplicated facts |
54
+ | Multi-hop questions | Weak | Not applicable | Graph traversal connects facts across documents |
55
+ | Same fact in many documents | Repeated in every retrieval | Not addressed | Merged into one node |
56
+ | Context sent per query | Whole chunks | The compressed prompt | Only the relevant sub-graph |
57
+ | Meaning-loss check | None | Text similarity | Round-trip validation with a confidence score |
58
+ | Adding documents | Re-chunk and re-embed | Not applicable | Merges into the existing graph |
59
+
60
+ ## Features
61
+
62
+ - **Text to semantic graph**: entity and relation extraction, with optional coreference resolution and transformer-based relations
63
+ - **Canonicalization and deduplication**: one canonical node per fact, across one document or many
64
+ - **Compact notation**: a low-token representation for LLM context injection, decodable back to natural language
65
+ - **Hybrid retrieval**: vector similarity search plus multi-hop graph traversal, under a `max_tokens` budget
66
+ - **Round-trip validation**: a confidence score for how much meaning the notation keeps
67
+ - **Incremental knowledge base**: new documents merge into the existing graph; save and load as a single `.noema` file
68
+ - **Streaming ingestion**: batched ingestion with checkpoints for large document sets
69
+ - **Persistent backends**: optional Neo4j and RDF stores for larger knowledge bases
70
+ - **Framework integrations**: LangChain and LlamaIndex retrievers, plus OpenAI and Anthropic token counting
71
+ - **Command-line tool**: `noema` for compression, graph building, querying and inspection
72
+ - **Benchmark suite**: reproducible comparison against plain-chunk RAG and full-context stuffing
73
+
74
+ ## Quick look
75
+
76
+ ```python
77
+ import noema
78
+
79
+ kb = noema.KnowledgeBase()
80
+ kb.ingest(documents)
81
+ context = kb.retrieve("Who is Google's CEO?", max_tokens=200)
82
+
83
+ prompt = f"{context.text}\n\nQuestion: Who is Google's CEO?"
84
+ ```
85
+
86
+ ## Use cases
87
+
88
+ - Cutting LLM token costs in RAG pipelines and long-context applications
89
+ - Multi-hop question answering over facts spread across several documents
90
+ - Building a lightweight knowledge graph from text without hand-written schemas
91
+ - Keeping a knowledge base up to date as new documents arrive
92
+
93
+ ## Documentation
94
+
95
+ Installation, usage guides, CLI and integration docs are on the project Wiki.
96
+
97
+ ## Project status
98
+
99
+ Noema is under active development. The core pipeline, storage, retrieval, integrations, CLI
100
+ and benchmark suite are implemented; the public API may still change before 1.0.
101
+
102
+ ## License
103
+
104
+ Noema is licensed under the [Apache License 2.0](LICENSE).
105
+
106
+ <sub>Keywords: RAG, retrieval-augmented generation, knowledge graph, GraphRAG, LLM context
107
+ compression, prompt compression, token reduction, semantic compression, entity and relation
108
+ extraction, multi-hop question answering, LangChain, LlamaIndex, Neo4j, RDF, Python.</sub>
@@ -0,0 +1,5 @@
1
+ """Benchmark suite comparing noema.KnowledgeBase against a plain-chunk RAG
2
+ baseline and a text-only compressor, on a large synthetic corpus with
3
+ known-answer questions. Development/evaluation tooling, not part of the
4
+ published noema package -- run via `uv run benchmarks/run_benchmark.py`.
5
+ """
@@ -0,0 +1,171 @@
1
+ """Baseline retrieval systems to compare against noema.KnowledgeBase:
2
+ plain-chunk RAG, naive full-context stuffing, and a text-only prompt
3
+ compressor.
4
+
5
+ All are intentionally simple, dependency-light reference implementations
6
+ -- not a specific commercial product -- so the benchmark compares *shapes*
7
+ of approach (raw chunks vs. the whole corpus vs. compressed chunks vs.
8
+ canonical graph facts) rather than one library's tuning against another's.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from functools import lru_cache
15
+
16
+ import numpy as np
17
+ from sentence_transformers import SentenceTransformer
18
+
19
+ from noema.compress import count_tokens
20
+
21
+ DEFAULT_EMBEDDING_MODEL = "all-MiniLM-L6-v2"
22
+ DEFAULT_CHUNK_TOKENS = 60
23
+ DEFAULT_TOP_K = 5
24
+
25
+ _SENTENCE_SPLIT = re.compile(r"(?<=[.!?])\s+")
26
+
27
+
28
+ @lru_cache(maxsize=2)
29
+ def _load_model(model_name: str = DEFAULT_EMBEDDING_MODEL) -> SentenceTransformer:
30
+ return SentenceTransformer(model_name)
31
+
32
+
33
+ def _split_sentences(text: str) -> list[str]:
34
+ return [s.strip() for s in _SENTENCE_SPLIT.split(text.strip()) if s.strip()]
35
+
36
+
37
+ def _chunk_document(text: str, chunk_tokens: int) -> list[str]:
38
+ """Group consecutive sentences into chunks of up to `chunk_tokens`
39
+ tokens each, the standard fixed-size chunking a plain-text RAG pipeline
40
+ would use -- no sentence is split, chunks just stop growing once the
41
+ next sentence would exceed the budget.
42
+ """
43
+ sentences = _split_sentences(text)
44
+ chunks: list[str] = []
45
+ current: list[str] = []
46
+ current_tokens = 0
47
+
48
+ for sentence in sentences:
49
+ sentence_tokens = count_tokens(sentence)
50
+ if current and current_tokens + sentence_tokens > chunk_tokens:
51
+ chunks.append(" ".join(current))
52
+ current = []
53
+ current_tokens = 0
54
+ current.append(sentence)
55
+ current_tokens += sentence_tokens
56
+
57
+ if current:
58
+ chunks.append(" ".join(current))
59
+ return chunks
60
+
61
+
62
+ class NaiveChunkRAG:
63
+ """Fixed-size chunk + embed + top-k retrieval, the traditional RAG
64
+ baseline: chunks are embedded whole and returned verbatim, with no
65
+ deduplication or cross-document structure.
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ chunk_tokens: int = DEFAULT_CHUNK_TOKENS,
71
+ embedding_model: str = DEFAULT_EMBEDDING_MODEL,
72
+ ) -> None:
73
+ self._chunk_tokens = chunk_tokens
74
+ self._embedding_model = embedding_model
75
+ self._chunks: list[str] = []
76
+ self._embeddings: np.ndarray | None = None
77
+
78
+ def build(self, documents: list[str]) -> None:
79
+ self._chunks = [
80
+ chunk for document in documents for chunk in _chunk_document(document, self._chunk_tokens)
81
+ ]
82
+ model = _load_model(self._embedding_model)
83
+ self._embeddings = model.encode(self._chunks, normalize_embeddings=True)
84
+
85
+ def retrieve(self, query: str, max_tokens: int, top_k: int = DEFAULT_TOP_K) -> str:
86
+ """Embed `query`, take the top_k most similar chunks, and
87
+ concatenate them verbatim (in similarity order) until `max_tokens`
88
+ would be exceeded.
89
+ """
90
+ if self._embeddings is None or not self._chunks:
91
+ return ""
92
+
93
+ model = _load_model(self._embedding_model)
94
+ query_vec = model.encode([query], normalize_embeddings=True)[0]
95
+ scores = self._embeddings @ query_vec
96
+ ranked_indices = np.argsort(-scores)[:top_k]
97
+
98
+ selected: list[str] = []
99
+ used_tokens = 0
100
+ for idx in ranked_indices:
101
+ chunk = self._chunks[int(idx)]
102
+ chunk_tokens = count_tokens(chunk)
103
+ if selected and used_tokens + chunk_tokens > max_tokens:
104
+ break
105
+ selected.append(chunk)
106
+ used_tokens += chunk_tokens
107
+ return "\n".join(selected)
108
+
109
+
110
+ class FullContextBaseline:
111
+ """Naive full-context stuffing: every query gets the entire corpus as
112
+ context. Retrieval accuracy is the ceiling (nothing is left out) and
113
+ token cost is the worst case, so it bounds the other systems.
114
+ """
115
+
116
+ def __init__(self) -> None:
117
+ self._text = ""
118
+
119
+ def build(self, documents: list[str]) -> None:
120
+ self._text = "\n".join(documents)
121
+
122
+ def retrieve(self, query: str, max_tokens: int | None = None) -> str:
123
+ """Return the whole corpus; `query` and `max_tokens` are ignored."""
124
+ return self._text
125
+
126
+
127
+ class TextOnlyCompressor:
128
+ """A structure-agnostic prompt compressor: starts from the same
129
+ retrieved chunks as NaiveChunkRAG, then compresses by keeping only the
130
+ individual sentences most relevant to the query (ranked by embedding
131
+ similarity) instead of whole chunks -- smaller than naive RAG, but
132
+ still text in, text out, with no notion of entities or facts.
133
+ """
134
+
135
+ def __init__(
136
+ self,
137
+ chunk_tokens: int = DEFAULT_CHUNK_TOKENS,
138
+ embedding_model: str = DEFAULT_EMBEDDING_MODEL,
139
+ candidate_chunks: int = DEFAULT_TOP_K,
140
+ ) -> None:
141
+ self._chunk_rag = NaiveChunkRAG(chunk_tokens=chunk_tokens, embedding_model=embedding_model)
142
+ self._embedding_model = embedding_model
143
+ self._candidate_chunks = candidate_chunks
144
+
145
+ def build(self, documents: list[str]) -> None:
146
+ self._chunk_rag.build(documents)
147
+
148
+ def retrieve(self, query: str, max_tokens: int) -> str:
149
+ candidate_text = self._chunk_rag.retrieve(
150
+ query, max_tokens=max_tokens * 4, top_k=self._candidate_chunks
151
+ )
152
+ sentences = _split_sentences(candidate_text)
153
+ if not sentences:
154
+ return ""
155
+
156
+ model = _load_model(self._embedding_model)
157
+ query_vec = model.encode([query], normalize_embeddings=True)[0]
158
+ sentence_vecs = model.encode(sentences, normalize_embeddings=True)
159
+ scores = sentence_vecs @ query_vec
160
+ ranked_indices = np.argsort(-scores)
161
+
162
+ selected: list[str] = []
163
+ used_tokens = 0
164
+ for idx in ranked_indices:
165
+ sentence = sentences[int(idx)]
166
+ sentence_tokens = count_tokens(sentence)
167
+ if selected and used_tokens + sentence_tokens > max_tokens:
168
+ break
169
+ selected.append(sentence)
170
+ used_tokens += sentence_tokens
171
+ return " ".join(selected)