knowledge-retriever 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.
- knowledge_retriever-0.1.0/LICENSE +202 -0
- knowledge_retriever-0.1.0/PKG-INFO +109 -0
- knowledge_retriever-0.1.0/README.md +92 -0
- knowledge_retriever-0.1.0/knowledge_retriever.egg-info/PKG-INFO +109 -0
- knowledge_retriever-0.1.0/knowledge_retriever.egg-info/SOURCES.txt +10 -0
- knowledge_retriever-0.1.0/knowledge_retriever.egg-info/dependency_links.txt +1 -0
- knowledge_retriever-0.1.0/knowledge_retriever.egg-info/entry_points.txt +2 -0
- knowledge_retriever-0.1.0/knowledge_retriever.egg-info/top_level.txt +1 -0
- knowledge_retriever-0.1.0/knowledge_retriever.py +525 -0
- knowledge_retriever-0.1.0/pyproject.toml +28 -0
- knowledge_retriever-0.1.0/setup.cfg +4 -0
- knowledge_retriever-0.1.0/tests/test_knowledge_retriever.py +156 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: knowledge-retriever
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 检索知识算子包:全文检索/九大元类/图谱多跳/双通道装配/缺口登记,纯标准库单文件 | Knowledge retrieval operator pack (pure stdlib, single file)
|
|
5
|
+
Author: tanbopiao
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://www.huodouai.com/whitepaper/knowledge-retriever-whitepaper.html
|
|
8
|
+
Project-URL: Repository, https://github.com/tanbopiao/knowledge-retriever
|
|
9
|
+
Keywords: knowledge,retrieval,knowledge-graph,rag,agent
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Topic :: Text Processing :: Indexing
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
<!-- mcp-name: io.github.tanbopiao/knowledge-retriever -->
|
|
19
|
+
# knowledge-retriever 检索知识算子包
|
|
20
|
+
|
|
21
|
+
检索知识算子包:把六篇检索知识线白皮书的算子可迁移部分收编为纯标准库单文件。
|
|
22
|
+
Knowledge retrieval operator pack — pure stdlib, single file.
|
|
23
|
+
|
|
24
|
+
**官方发布页**:<https://www.huodouai.com/whitepaper/knowledge-retriever-whitepaper.html>
|
|
25
|
+
|
|
26
|
+
## 白皮书来源(互跳)
|
|
27
|
+
|
|
28
|
+
- [知识检索引擎 KNOWLEDGE-RETRIEVER](https://www.huodouai.com/whitepaper/knowledge-retriever-whitepaper.html)
|
|
29
|
+
- [全域知识关联引擎](https://www.huodouai.com/whitepaper/knowledge-association-engine-whitepaper.html)
|
|
30
|
+
- [知识图谱构建实录 V4](https://www.huodouai.com/whitepaper/knowledge-graph-construction.html)
|
|
31
|
+
- [P1 双通道按需检索引擎](https://www.huodouai.com/whitepaper/p1-dual-channel-indexing-engine-v1.0.html)
|
|
32
|
+
- [知识晶格化设计](https://www.huodouai.com/whitepaper/crystal-lattice.html)
|
|
33
|
+
- [Octop 知识中枢 P2 进化实录](https://www.huodouai.com/whitepaper/octop-agent-evolution.html)
|
|
34
|
+
|
|
35
|
+
## 安装
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install knowledge-retriever
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
零第三方依赖,纯标准库单文件(`knowledge_retriever.py`,约 520 行)。
|
|
42
|
+
|
|
43
|
+
## 12 项第一圈算子
|
|
44
|
+
|
|
45
|
+
| # | 算子 | 说明 |
|
|
46
|
+
|---|------|------|
|
|
47
|
+
| 1 | 条目模型与落盘 | JSON 索引单文件;晶胞三维晶面指数(元类×命名空间×状态轴) |
|
|
48
|
+
| 2 | 全文检索 | 中英混合分词+匹配度评分;禁编造命中 |
|
|
49
|
+
| 3 | 九大元类过滤 | 公理/定理/方法/数据/案例/决策/创意/风险/协议;入库强制带标签 |
|
|
50
|
+
| 4 | 标签聚类与关联推荐 | 标签重叠计算 |
|
|
51
|
+
| 5 | 索引管理四命令 | index / search / related / tags |
|
|
52
|
+
| 6 | 三元组图谱 | SQLite 落库+8 类多跳查询(stats/predicate/2hop/3hop/ns/type/confidence/entity) |
|
|
53
|
+
| 7 | 三维晶格索引 | 元类 × 命名空间 × 时间 |
|
|
54
|
+
| 8 | 意图分类器 | 6 类意图关键词加权打分(规则版) |
|
|
55
|
+
| 9 | 缺口登记 | 检索全空落盘缺口;重建时生成「待补于」边 |
|
|
56
|
+
| 10 | 双通道装配 | 静态内核强制载入+动态按需+70% 上限+装配审计 |
|
|
57
|
+
| 11 | 平移复用铁律 | 同 sha 锚定,禁止复制改造(AXIOM-REUSE-NO-REDO-001) |
|
|
58
|
+
| 12 | 注册四步校验 | metadata → index → graph → lock,缺一不落账 |
|
|
59
|
+
|
|
60
|
+
## 用法
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
knowledge-retriever add truth.demo.001 "结论:纯标准库路线可行" 决策 kernel.demo --tags 检索,标准库
|
|
64
|
+
knowledge-retriever search "标准库 检索"
|
|
65
|
+
knowledge-retriever related truth.demo.001
|
|
66
|
+
knowledge-retriever tags
|
|
67
|
+
knowledge-retriever graph stats # 图谱规模
|
|
68
|
+
knowledge-retriever graph predicate # 谓词分布
|
|
69
|
+
knowledge-retriever graph 2hop 确权于 属于 # 两跳
|
|
70
|
+
knowledge-retriever lattice --meta-class 方法
|
|
71
|
+
knowledge-retriever classify "图谱规模有多少三元组"
|
|
72
|
+
knowledge-retriever gap "体系目前有哪些对外协议"
|
|
73
|
+
knowledge-retriever assemble "标准库 检索"
|
|
74
|
+
knowledge-retriever register truth.demo.004 "注册四步全通验证" 协议 kernel.demo
|
|
75
|
+
knowledge-retriever selftest
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Python API:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
from knowledge_retriever import KnowledgeRetriever
|
|
82
|
+
kr = KnowledgeRetriever()
|
|
83
|
+
kr.add("t.1", "结论:可行", "决策", "kernel.demo", tags=["检索"])
|
|
84
|
+
kr.search("可行")
|
|
85
|
+
kr.build_graph()
|
|
86
|
+
kr.graph_query("stats")
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## 诚实边界
|
|
90
|
+
|
|
91
|
+
- 规则版检索/意图分类非模型级;语义检索为接口占位(预留向量检索对接面)。
|
|
92
|
+
- 图谱为 SQLite 规则版,非 DuckDB 原版;DuckDB 可作可选依赖另配。
|
|
93
|
+
- Web 服务线(Octop 前端、nginx 反代、统一查询网关)不在包内。
|
|
94
|
+
- 落盘位置:`~/.knowledge_retriever/`(可用环境变量 `KNOWLEDGE_RETRIEVER_HOME` 覆盖)。
|
|
95
|
+
|
|
96
|
+
## 自检
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
knowledge-retriever selftest # 内置 22 例
|
|
100
|
+
python tests/test_knowledge_retriever.py # 单测 20 例
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## 许可
|
|
104
|
+
|
|
105
|
+
Apache-2.0
|
|
106
|
+
|
|
107
|
+
## Skill 封装
|
|
108
|
+
|
|
109
|
+
仓库根目录带 `SKILL.md`(Agent Skills 格式):name/description 前言+用法与输出说明,可直接挂入支持技能的智能体。
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
<!-- mcp-name: io.github.tanbopiao/knowledge-retriever -->
|
|
2
|
+
# knowledge-retriever 检索知识算子包
|
|
3
|
+
|
|
4
|
+
检索知识算子包:把六篇检索知识线白皮书的算子可迁移部分收编为纯标准库单文件。
|
|
5
|
+
Knowledge retrieval operator pack — pure stdlib, single file.
|
|
6
|
+
|
|
7
|
+
**官方发布页**:<https://www.huodouai.com/whitepaper/knowledge-retriever-whitepaper.html>
|
|
8
|
+
|
|
9
|
+
## 白皮书来源(互跳)
|
|
10
|
+
|
|
11
|
+
- [知识检索引擎 KNOWLEDGE-RETRIEVER](https://www.huodouai.com/whitepaper/knowledge-retriever-whitepaper.html)
|
|
12
|
+
- [全域知识关联引擎](https://www.huodouai.com/whitepaper/knowledge-association-engine-whitepaper.html)
|
|
13
|
+
- [知识图谱构建实录 V4](https://www.huodouai.com/whitepaper/knowledge-graph-construction.html)
|
|
14
|
+
- [P1 双通道按需检索引擎](https://www.huodouai.com/whitepaper/p1-dual-channel-indexing-engine-v1.0.html)
|
|
15
|
+
- [知识晶格化设计](https://www.huodouai.com/whitepaper/crystal-lattice.html)
|
|
16
|
+
- [Octop 知识中枢 P2 进化实录](https://www.huodouai.com/whitepaper/octop-agent-evolution.html)
|
|
17
|
+
|
|
18
|
+
## 安装
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install knowledge-retriever
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
零第三方依赖,纯标准库单文件(`knowledge_retriever.py`,约 520 行)。
|
|
25
|
+
|
|
26
|
+
## 12 项第一圈算子
|
|
27
|
+
|
|
28
|
+
| # | 算子 | 说明 |
|
|
29
|
+
|---|------|------|
|
|
30
|
+
| 1 | 条目模型与落盘 | JSON 索引单文件;晶胞三维晶面指数(元类×命名空间×状态轴) |
|
|
31
|
+
| 2 | 全文检索 | 中英混合分词+匹配度评分;禁编造命中 |
|
|
32
|
+
| 3 | 九大元类过滤 | 公理/定理/方法/数据/案例/决策/创意/风险/协议;入库强制带标签 |
|
|
33
|
+
| 4 | 标签聚类与关联推荐 | 标签重叠计算 |
|
|
34
|
+
| 5 | 索引管理四命令 | index / search / related / tags |
|
|
35
|
+
| 6 | 三元组图谱 | SQLite 落库+8 类多跳查询(stats/predicate/2hop/3hop/ns/type/confidence/entity) |
|
|
36
|
+
| 7 | 三维晶格索引 | 元类 × 命名空间 × 时间 |
|
|
37
|
+
| 8 | 意图分类器 | 6 类意图关键词加权打分(规则版) |
|
|
38
|
+
| 9 | 缺口登记 | 检索全空落盘缺口;重建时生成「待补于」边 |
|
|
39
|
+
| 10 | 双通道装配 | 静态内核强制载入+动态按需+70% 上限+装配审计 |
|
|
40
|
+
| 11 | 平移复用铁律 | 同 sha 锚定,禁止复制改造(AXIOM-REUSE-NO-REDO-001) |
|
|
41
|
+
| 12 | 注册四步校验 | metadata → index → graph → lock,缺一不落账 |
|
|
42
|
+
|
|
43
|
+
## 用法
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
knowledge-retriever add truth.demo.001 "结论:纯标准库路线可行" 决策 kernel.demo --tags 检索,标准库
|
|
47
|
+
knowledge-retriever search "标准库 检索"
|
|
48
|
+
knowledge-retriever related truth.demo.001
|
|
49
|
+
knowledge-retriever tags
|
|
50
|
+
knowledge-retriever graph stats # 图谱规模
|
|
51
|
+
knowledge-retriever graph predicate # 谓词分布
|
|
52
|
+
knowledge-retriever graph 2hop 确权于 属于 # 两跳
|
|
53
|
+
knowledge-retriever lattice --meta-class 方法
|
|
54
|
+
knowledge-retriever classify "图谱规模有多少三元组"
|
|
55
|
+
knowledge-retriever gap "体系目前有哪些对外协议"
|
|
56
|
+
knowledge-retriever assemble "标准库 检索"
|
|
57
|
+
knowledge-retriever register truth.demo.004 "注册四步全通验证" 协议 kernel.demo
|
|
58
|
+
knowledge-retriever selftest
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Python API:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from knowledge_retriever import KnowledgeRetriever
|
|
65
|
+
kr = KnowledgeRetriever()
|
|
66
|
+
kr.add("t.1", "结论:可行", "决策", "kernel.demo", tags=["检索"])
|
|
67
|
+
kr.search("可行")
|
|
68
|
+
kr.build_graph()
|
|
69
|
+
kr.graph_query("stats")
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## 诚实边界
|
|
73
|
+
|
|
74
|
+
- 规则版检索/意图分类非模型级;语义检索为接口占位(预留向量检索对接面)。
|
|
75
|
+
- 图谱为 SQLite 规则版,非 DuckDB 原版;DuckDB 可作可选依赖另配。
|
|
76
|
+
- Web 服务线(Octop 前端、nginx 反代、统一查询网关)不在包内。
|
|
77
|
+
- 落盘位置:`~/.knowledge_retriever/`(可用环境变量 `KNOWLEDGE_RETRIEVER_HOME` 覆盖)。
|
|
78
|
+
|
|
79
|
+
## 自检
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
knowledge-retriever selftest # 内置 22 例
|
|
83
|
+
python tests/test_knowledge_retriever.py # 单测 20 例
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## 许可
|
|
87
|
+
|
|
88
|
+
Apache-2.0
|
|
89
|
+
|
|
90
|
+
## Skill 封装
|
|
91
|
+
|
|
92
|
+
仓库根目录带 `SKILL.md`(Agent Skills 格式):name/description 前言+用法与输出说明,可直接挂入支持技能的智能体。
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: knowledge-retriever
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 检索知识算子包:全文检索/九大元类/图谱多跳/双通道装配/缺口登记,纯标准库单文件 | Knowledge retrieval operator pack (pure stdlib, single file)
|
|
5
|
+
Author: tanbopiao
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://www.huodouai.com/whitepaper/knowledge-retriever-whitepaper.html
|
|
8
|
+
Project-URL: Repository, https://github.com/tanbopiao/knowledge-retriever
|
|
9
|
+
Keywords: knowledge,retrieval,knowledge-graph,rag,agent
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Topic :: Text Processing :: Indexing
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
<!-- mcp-name: io.github.tanbopiao/knowledge-retriever -->
|
|
19
|
+
# knowledge-retriever 检索知识算子包
|
|
20
|
+
|
|
21
|
+
检索知识算子包:把六篇检索知识线白皮书的算子可迁移部分收编为纯标准库单文件。
|
|
22
|
+
Knowledge retrieval operator pack — pure stdlib, single file.
|
|
23
|
+
|
|
24
|
+
**官方发布页**:<https://www.huodouai.com/whitepaper/knowledge-retriever-whitepaper.html>
|
|
25
|
+
|
|
26
|
+
## 白皮书来源(互跳)
|
|
27
|
+
|
|
28
|
+
- [知识检索引擎 KNOWLEDGE-RETRIEVER](https://www.huodouai.com/whitepaper/knowledge-retriever-whitepaper.html)
|
|
29
|
+
- [全域知识关联引擎](https://www.huodouai.com/whitepaper/knowledge-association-engine-whitepaper.html)
|
|
30
|
+
- [知识图谱构建实录 V4](https://www.huodouai.com/whitepaper/knowledge-graph-construction.html)
|
|
31
|
+
- [P1 双通道按需检索引擎](https://www.huodouai.com/whitepaper/p1-dual-channel-indexing-engine-v1.0.html)
|
|
32
|
+
- [知识晶格化设计](https://www.huodouai.com/whitepaper/crystal-lattice.html)
|
|
33
|
+
- [Octop 知识中枢 P2 进化实录](https://www.huodouai.com/whitepaper/octop-agent-evolution.html)
|
|
34
|
+
|
|
35
|
+
## 安装
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install knowledge-retriever
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
零第三方依赖,纯标准库单文件(`knowledge_retriever.py`,约 520 行)。
|
|
42
|
+
|
|
43
|
+
## 12 项第一圈算子
|
|
44
|
+
|
|
45
|
+
| # | 算子 | 说明 |
|
|
46
|
+
|---|------|------|
|
|
47
|
+
| 1 | 条目模型与落盘 | JSON 索引单文件;晶胞三维晶面指数(元类×命名空间×状态轴) |
|
|
48
|
+
| 2 | 全文检索 | 中英混合分词+匹配度评分;禁编造命中 |
|
|
49
|
+
| 3 | 九大元类过滤 | 公理/定理/方法/数据/案例/决策/创意/风险/协议;入库强制带标签 |
|
|
50
|
+
| 4 | 标签聚类与关联推荐 | 标签重叠计算 |
|
|
51
|
+
| 5 | 索引管理四命令 | index / search / related / tags |
|
|
52
|
+
| 6 | 三元组图谱 | SQLite 落库+8 类多跳查询(stats/predicate/2hop/3hop/ns/type/confidence/entity) |
|
|
53
|
+
| 7 | 三维晶格索引 | 元类 × 命名空间 × 时间 |
|
|
54
|
+
| 8 | 意图分类器 | 6 类意图关键词加权打分(规则版) |
|
|
55
|
+
| 9 | 缺口登记 | 检索全空落盘缺口;重建时生成「待补于」边 |
|
|
56
|
+
| 10 | 双通道装配 | 静态内核强制载入+动态按需+70% 上限+装配审计 |
|
|
57
|
+
| 11 | 平移复用铁律 | 同 sha 锚定,禁止复制改造(AXIOM-REUSE-NO-REDO-001) |
|
|
58
|
+
| 12 | 注册四步校验 | metadata → index → graph → lock,缺一不落账 |
|
|
59
|
+
|
|
60
|
+
## 用法
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
knowledge-retriever add truth.demo.001 "结论:纯标准库路线可行" 决策 kernel.demo --tags 检索,标准库
|
|
64
|
+
knowledge-retriever search "标准库 检索"
|
|
65
|
+
knowledge-retriever related truth.demo.001
|
|
66
|
+
knowledge-retriever tags
|
|
67
|
+
knowledge-retriever graph stats # 图谱规模
|
|
68
|
+
knowledge-retriever graph predicate # 谓词分布
|
|
69
|
+
knowledge-retriever graph 2hop 确权于 属于 # 两跳
|
|
70
|
+
knowledge-retriever lattice --meta-class 方法
|
|
71
|
+
knowledge-retriever classify "图谱规模有多少三元组"
|
|
72
|
+
knowledge-retriever gap "体系目前有哪些对外协议"
|
|
73
|
+
knowledge-retriever assemble "标准库 检索"
|
|
74
|
+
knowledge-retriever register truth.demo.004 "注册四步全通验证" 协议 kernel.demo
|
|
75
|
+
knowledge-retriever selftest
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Python API:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
from knowledge_retriever import KnowledgeRetriever
|
|
82
|
+
kr = KnowledgeRetriever()
|
|
83
|
+
kr.add("t.1", "结论:可行", "决策", "kernel.demo", tags=["检索"])
|
|
84
|
+
kr.search("可行")
|
|
85
|
+
kr.build_graph()
|
|
86
|
+
kr.graph_query("stats")
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## 诚实边界
|
|
90
|
+
|
|
91
|
+
- 规则版检索/意图分类非模型级;语义检索为接口占位(预留向量检索对接面)。
|
|
92
|
+
- 图谱为 SQLite 规则版,非 DuckDB 原版;DuckDB 可作可选依赖另配。
|
|
93
|
+
- Web 服务线(Octop 前端、nginx 反代、统一查询网关)不在包内。
|
|
94
|
+
- 落盘位置:`~/.knowledge_retriever/`(可用环境变量 `KNOWLEDGE_RETRIEVER_HOME` 覆盖)。
|
|
95
|
+
|
|
96
|
+
## 自检
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
knowledge-retriever selftest # 内置 22 例
|
|
100
|
+
python tests/test_knowledge_retriever.py # 单测 20 例
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## 许可
|
|
104
|
+
|
|
105
|
+
Apache-2.0
|
|
106
|
+
|
|
107
|
+
## Skill 封装
|
|
108
|
+
|
|
109
|
+
仓库根目录带 `SKILL.md`(Agent Skills 格式):name/description 前言+用法与输出说明,可直接挂入支持技能的智能体。
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
knowledge_retriever.py
|
|
4
|
+
pyproject.toml
|
|
5
|
+
knowledge_retriever.egg-info/PKG-INFO
|
|
6
|
+
knowledge_retriever.egg-info/SOURCES.txt
|
|
7
|
+
knowledge_retriever.egg-info/dependency_links.txt
|
|
8
|
+
knowledge_retriever.egg-info/entry_points.txt
|
|
9
|
+
knowledge_retriever.egg-info/top_level.txt
|
|
10
|
+
tests/test_knowledge_retriever.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
knowledge_retriever
|
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""knowledge-retriever — 检索知识算子包(纯标准库单文件)
|
|
4
|
+
|
|
5
|
+
白皮书建仓第五刀:收编六篇检索知识线白皮书的算子可迁移部分。
|
|
6
|
+
- 知识检索引擎 KNOWLEDGE-RETRIEVER:全文检索/标签聚类/关联推荐/九大元类/索引管理
|
|
7
|
+
- 全域知识关联引擎:注册四步校验(metadata→index→graph→lock)
|
|
8
|
+
- 知识图谱构建实录 V4:三元组抽取+SQLite 落库+8 类多跳查询(SQLite 替代 DuckDB)
|
|
9
|
+
- P1 双通道按需检索引擎:静态内核强制载入+动态按需+70% 上限+装配审计
|
|
10
|
+
- 知识晶格化设计:晶胞三维晶面指数+平移复用铁律 AXIOM-REUSE-NO-REDO-001
|
|
11
|
+
- Octop 知识中枢 P2:6 类意图加权分类器+缺口登记「待补于」边
|
|
12
|
+
|
|
13
|
+
诚实边界:规则版检索/意图分类非模型级;语义检索占位;图谱为 SQLite 规则版;
|
|
14
|
+
Web 服务线(Octop 前端/nginx/统一网关)不在包内。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import hashlib
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import sqlite3
|
|
23
|
+
import sys
|
|
24
|
+
import time
|
|
25
|
+
|
|
26
|
+
VERSION = "0.1.0"
|
|
27
|
+
META_CLASSES = ("公理", "定理", "方法", "数据", "案例", "决策", "创意", "风险", "协议")
|
|
28
|
+
CONF_LEVELS = {"S": 0.95, "A": 0.85, "B": 0.70, "C": 0.40}
|
|
29
|
+
TOKEN_BUDGET_STATIC = 2000
|
|
30
|
+
DYNAMIC_CAP = 0.70
|
|
31
|
+
INTENTS = {
|
|
32
|
+
"stats": [("图谱规模", 0.9), ("三元组", 0.9), ("图谱", 0.45), ("多少条", 0.6)],
|
|
33
|
+
"2hop": [("谁确权", 0.95), ("确权", 0.9), ("归属", 0.85), ("属于", 0.7)],
|
|
34
|
+
"3hop": [("三跳", 0.95), ("跨域", 0.9), ("决策类", 0.9), ("各有多少", 0.7)],
|
|
35
|
+
"ns": [("命名空间", 0.9), ("namespace", 0.9)],
|
|
36
|
+
"predicate": [("谓词", 0.9), ("关系类型", 0.9)],
|
|
37
|
+
"type": [("类型分布", 0.9), ("类型为", 0.6), ("实体类型", 0.9)],
|
|
38
|
+
}
|
|
39
|
+
BASE_RELATIONS = ("确权于", "属于", "关联", "派生")
|
|
40
|
+
DEPLOY_RELATION = "部署于"
|
|
41
|
+
GAP_RELATION = "待补于"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def now():
|
|
45
|
+
return int(time.time())
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def est_tokens(text):
|
|
49
|
+
"""中文 1 字 1 token,英文 4 字符 1 token(对齐温故口径)。"""
|
|
50
|
+
if not text:
|
|
51
|
+
return 0
|
|
52
|
+
cjk = len(re.findall(r"[\u4e00-\u9fff]", text))
|
|
53
|
+
other = len(text) - cjk
|
|
54
|
+
return cjk + (other + 3) // 4
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def tokenize(text):
|
|
58
|
+
"""中英混合分词:汉字单字+英文单词小写。"""
|
|
59
|
+
return re.findall(r"[\u4e00-\u9fff]|[a-z0-9]+", (text or "").lower())
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def sha256(text):
|
|
63
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def match_score(query_terms, entry):
|
|
67
|
+
"""匹配度评分:查询词在 key/value/tags/namespace 中的加权命中。"""
|
|
68
|
+
hay = tokenize(entry.get("key", "") + " " + str(entry.get("value", ""))
|
|
69
|
+
+ " " + " ".join(entry.get("tags", [])) + " " + entry.get("namespace", ""))
|
|
70
|
+
hay_set = set(hay)
|
|
71
|
+
hits = sum(1 for t in query_terms if t in hay_set)
|
|
72
|
+
if not query_terms:
|
|
73
|
+
return 0.0
|
|
74
|
+
return hits / len(query_terms)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class KnowledgeRetriever:
|
|
78
|
+
def __init__(self, home=None, graph_path=None):
|
|
79
|
+
base = home or os.environ.get("KNOWLEDGE_RETRIEVER_HOME",
|
|
80
|
+
os.path.join(os.path.expanduser("~"), ".knowledge_retriever"))
|
|
81
|
+
os.makedirs(base, exist_ok=True)
|
|
82
|
+
self.index_path = os.path.join(base, "knowledge_index.json")
|
|
83
|
+
self.graph_path = graph_path or os.path.join(base, "kg.sqlite3")
|
|
84
|
+
self.audit_path = os.path.join(base, "assembly_audit.jsonl")
|
|
85
|
+
self._index = None
|
|
86
|
+
|
|
87
|
+
# ---------- 存储 ----------
|
|
88
|
+
def _load(self):
|
|
89
|
+
if self._index is None:
|
|
90
|
+
if os.path.exists(self.index_path):
|
|
91
|
+
with open(self.index_path, "r", encoding="utf-8") as f:
|
|
92
|
+
self._index = json.load(f)
|
|
93
|
+
else:
|
|
94
|
+
self._index = {"entries": [], "gaps": [], "locked": []}
|
|
95
|
+
return self._index
|
|
96
|
+
|
|
97
|
+
def _save(self):
|
|
98
|
+
with open(self.index_path, "w", encoding="utf-8") as f:
|
|
99
|
+
json.dump(self._index, f, ensure_ascii=False, indent=1)
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def entries(self):
|
|
103
|
+
return self._load()["entries"]
|
|
104
|
+
|
|
105
|
+
# ---------- 算子 1:条目模型与落盘(晶胞三维晶面指数) ----------
|
|
106
|
+
def add(self, key, value, meta_class, namespace, tags=None, source="manual",
|
|
107
|
+
confidence=None, version="v1", static=False):
|
|
108
|
+
if meta_class not in META_CLASSES:
|
|
109
|
+
raise ValueError("入库必须带九大元类标签,缺标签或非法标签拒绝:%r" % meta_class)
|
|
110
|
+
if not namespace:
|
|
111
|
+
raise ValueError("命名空间轴缺失,拒绝入库")
|
|
112
|
+
h = sha256(str(value))
|
|
113
|
+
for e in self.entries:
|
|
114
|
+
if e["sha"] == h and e["key"] != key:
|
|
115
|
+
raise ValueError("AXIOM-REUSE-NO-REDO-001:同一真值只产生一次,"
|
|
116
|
+
"禁止复制改造成新条目;请复用已有 key:%s" % e["key"])
|
|
117
|
+
if e["sha"] == h and e["key"] == key:
|
|
118
|
+
return {"status": "duplicate", "key": key}
|
|
119
|
+
if confidence is None:
|
|
120
|
+
confidence = self._auto_confidence(value, meta_class)
|
|
121
|
+
entry = {
|
|
122
|
+
"key": key, "value": value, "meta_class": meta_class,
|
|
123
|
+
"namespace": namespace, "tags": list(tags or []),
|
|
124
|
+
"confidence": confidence, "version": version, "source": source,
|
|
125
|
+
"sha": h, "ts": now(), "static": bool(static),
|
|
126
|
+
}
|
|
127
|
+
self.entries.append(entry)
|
|
128
|
+
self._save()
|
|
129
|
+
return {"status": "ok", "key": key, "sha": h[:12], "confidence": confidence}
|
|
130
|
+
|
|
131
|
+
def _auto_confidence(self, value, meta_class):
|
|
132
|
+
"""自动置信度:按内容长度+元类映射 S/A/B/C。"""
|
|
133
|
+
n = est_tokens(str(value))
|
|
134
|
+
if meta_class in ("公理", "协议") and n >= 20:
|
|
135
|
+
lvl = "S"
|
|
136
|
+
elif meta_class in ("决策", "定理") and n >= 10:
|
|
137
|
+
lvl = "A"
|
|
138
|
+
elif n >= 5:
|
|
139
|
+
lvl = "B"
|
|
140
|
+
else:
|
|
141
|
+
lvl = "C"
|
|
142
|
+
return CONF_LEVELS[lvl]
|
|
143
|
+
|
|
144
|
+
# ---------- 算子 2/3:全文检索+元类过滤(禁编造命中) ----------
|
|
145
|
+
def search(self, query, meta_class=None, namespace=None, min_confidence=0.0, limit=10):
|
|
146
|
+
terms = tokenize(query)
|
|
147
|
+
results = []
|
|
148
|
+
for e in self.entries:
|
|
149
|
+
if meta_class and e["meta_class"] != meta_class:
|
|
150
|
+
continue
|
|
151
|
+
if namespace and not e["namespace"].startswith(namespace):
|
|
152
|
+
continue
|
|
153
|
+
if e["confidence"] < min_confidence:
|
|
154
|
+
continue
|
|
155
|
+
s = match_score(terms, e)
|
|
156
|
+
if s > 0:
|
|
157
|
+
results.append((s, e))
|
|
158
|
+
results.sort(key=lambda x: (-x[0], -x[1]["confidence"]))
|
|
159
|
+
return [{"score": round(s, 3), "key": e["key"], "meta_class": e["meta_class"],
|
|
160
|
+
"namespace": e["namespace"], "confidence": e["confidence"],
|
|
161
|
+
"value": str(e["value"])[:120]} for s, e in results[:limit]]
|
|
162
|
+
|
|
163
|
+
# ---------- 算子 4:标签聚类与关联推荐 ----------
|
|
164
|
+
def related(self, key, limit=5):
|
|
165
|
+
target = next((e for e in self.entries if e["key"] == key), None)
|
|
166
|
+
if not target:
|
|
167
|
+
return []
|
|
168
|
+
tset = set(target.get("tags", []))
|
|
169
|
+
ns = target["namespace"].split(".")[0]
|
|
170
|
+
scored = []
|
|
171
|
+
for e in self.entries:
|
|
172
|
+
if e["key"] == key:
|
|
173
|
+
continue
|
|
174
|
+
overlap = len(tset & set(e.get("tags", [])))
|
|
175
|
+
same_ns = 1 if e["namespace"].split(".")[0] == ns else 0
|
|
176
|
+
score = overlap * 2 + same_ns
|
|
177
|
+
if score > 0:
|
|
178
|
+
scored.append((score, e["key"], overlap))
|
|
179
|
+
scored.sort(key=lambda x: (-x[0], x[1]))
|
|
180
|
+
return [{"key": k, "tag_overlap": o} for _, k, o in scored[:limit]]
|
|
181
|
+
|
|
182
|
+
def tag_clusters(self):
|
|
183
|
+
clusters = {}
|
|
184
|
+
for e in self.entries:
|
|
185
|
+
for t in e.get("tags", []):
|
|
186
|
+
clusters.setdefault(t, []).append(e["key"])
|
|
187
|
+
return {t: sorted(ks) for t, ks in sorted(clusters.items(), key=lambda x: -len(x[1]))}
|
|
188
|
+
|
|
189
|
+
# ---------- 算子 6:三元组抽取与图谱落库(SQLite) ----------
|
|
190
|
+
def _graph(self):
|
|
191
|
+
conn = sqlite3.connect(self.graph_path)
|
|
192
|
+
conn.execute("CREATE TABLE IF NOT EXISTS kg_triples (subject TEXT, predicate TEXT, object TEXT, sha TEXT, ts INTEGER)")
|
|
193
|
+
conn.execute("CREATE TABLE IF NOT EXISTS kg_entities (name TEXT, etype TEXT, namespace TEXT)")
|
|
194
|
+
conn.execute("CREATE TABLE IF NOT EXISTS kg_gaps (question TEXT, ts INTEGER, resolved INTEGER DEFAULT 0)")
|
|
195
|
+
return conn
|
|
196
|
+
|
|
197
|
+
ENTITY_TYPES = ("真值", "命名空间", "类型", "组件", "DID")
|
|
198
|
+
|
|
199
|
+
def build_graph(self):
|
|
200
|
+
"""从条目抽取三元组落库;同时处理缺口登记生成「待补于」边。"""
|
|
201
|
+
conn = self._graph()
|
|
202
|
+
conn.execute("DELETE FROM kg_triples")
|
|
203
|
+
conn.execute("DELETE FROM kg_entities")
|
|
204
|
+
n_ent = 0
|
|
205
|
+
for e in self.entries:
|
|
206
|
+
ns = e["namespace"]
|
|
207
|
+
conn.execute("INSERT INTO kg_entities VALUES (?,?,?)", (ns, "命名空间", ns))
|
|
208
|
+
conn.execute("INSERT INTO kg_entities VALUES (?,?,?)", (e["key"], "真值", ns))
|
|
209
|
+
conn.execute("INSERT INTO kg_triples VALUES (?,?,?,?,?)",
|
|
210
|
+
(e["key"], "确权于", ns, e["sha"], e["ts"]))
|
|
211
|
+
conn.execute("INSERT INTO kg_triples VALUES (?,?,?,?,?)",
|
|
212
|
+
(e["key"], "属于", e["meta_class"], e["sha"], e["ts"]))
|
|
213
|
+
n_ent += 2
|
|
214
|
+
for t in e.get("tags", []):
|
|
215
|
+
conn.execute("INSERT INTO kg_entities VALUES (?,?,?)", (t, "类型", ns))
|
|
216
|
+
conn.execute("INSERT INTO kg_triples VALUES (?,?,?,?,?)",
|
|
217
|
+
(e["key"], "关联", t, e["sha"], e["ts"]))
|
|
218
|
+
n_ent += 1
|
|
219
|
+
m = re.search(r"(?:部署于|deployed on)[::]?\s*(\S+)", str(e["value"]))
|
|
220
|
+
if m:
|
|
221
|
+
conn.execute("INSERT INTO kg_triples VALUES (?,?,?,?,?)",
|
|
222
|
+
(e["key"], DEPLOY_RELATION, m.group(1), e["sha"], e["ts"]))
|
|
223
|
+
# 第 7 算子:结论文本抽取
|
|
224
|
+
m = re.search(r"(?:结论|conclusion)[::]\s*(.+)", str(e["value"]))
|
|
225
|
+
if m:
|
|
226
|
+
conn.execute("INSERT INTO kg_triples VALUES (?,?,?,?,?)",
|
|
227
|
+
(e["key"], "结论", m.group(1)[:80], e["sha"], e["ts"]))
|
|
228
|
+
# 缺口 → 待补于边
|
|
229
|
+
for g in self._load()["gaps"]:
|
|
230
|
+
if g.get("resolved"):
|
|
231
|
+
continue
|
|
232
|
+
cands = self._gap_candidates(g["question"])
|
|
233
|
+
for c in cands:
|
|
234
|
+
conn.execute("INSERT INTO kg_triples VALUES (?,?,?,?,?)",
|
|
235
|
+
("gap:" + g["question"][:40], GAP_RELATION, c, "", g["ts"]))
|
|
236
|
+
g["resolved"] = 1
|
|
237
|
+
conn.commit()
|
|
238
|
+
stats = self.graph_query("stats")
|
|
239
|
+
conn.close()
|
|
240
|
+
return stats
|
|
241
|
+
|
|
242
|
+
def _gap_candidates(self, question):
|
|
243
|
+
"""从缺口问题文本抽取命中已有实体的候选(组件词表/显式引用)。"""
|
|
244
|
+
q = question.lower()
|
|
245
|
+
windows = {q[i:i + n] for n in (2, 3, 4) for i in range(max(len(q) - n + 1, 0))}
|
|
246
|
+
names = [e["key"] for e in self.entries] + sorted({e["namespace"] for e in self.entries})
|
|
247
|
+
out = []
|
|
248
|
+
for name in names:
|
|
249
|
+
nl = name.lower()
|
|
250
|
+
if any(w in nl for w in windows):
|
|
251
|
+
if name not in out:
|
|
252
|
+
out.append(name)
|
|
253
|
+
return out[:5]
|
|
254
|
+
|
|
255
|
+
# ---------- 算子 6:8 类多跳查询 ----------
|
|
256
|
+
def graph_query(self, kind, arg=None, arg2=None):
|
|
257
|
+
conn = self._graph()
|
|
258
|
+
cur = conn.cursor()
|
|
259
|
+
try:
|
|
260
|
+
if kind == "stats":
|
|
261
|
+
cur.execute("SELECT COUNT(*) FROM kg_triples")
|
|
262
|
+
t = cur.fetchone()[0]
|
|
263
|
+
cur.execute("SELECT COUNT(*) FROM kg_entities")
|
|
264
|
+
e = cur.fetchone()[0]
|
|
265
|
+
return {"triples": t, "entities": e}
|
|
266
|
+
if kind == "predicate":
|
|
267
|
+
cur.execute("SELECT predicate, COUNT(*) FROM kg_triples GROUP BY predicate ORDER BY COUNT(*) DESC")
|
|
268
|
+
return {p: c for p, c in cur.fetchall()}
|
|
269
|
+
if kind == "2hop":
|
|
270
|
+
cur.execute("SELECT t1.subject, t1.predicate, t2.predicate, t2.object FROM kg_triples t1 "
|
|
271
|
+
"JOIN kg_triples t2 ON t1.object = t2.subject WHERE t1.predicate=? AND t2.predicate=? LIMIT 50",
|
|
272
|
+
(arg or "确权于", arg2 or "属于"))
|
|
273
|
+
return [{"subject": r[0], "path": r[1] + "→" + r[2], "object": r[3]} for r in cur.fetchall()]
|
|
274
|
+
if kind == "3hop":
|
|
275
|
+
cur.execute("SELECT t1.subject, t2.predicate, t3.object FROM kg_triples t1 "
|
|
276
|
+
"JOIN kg_triples t2 ON t1.object = t2.subject "
|
|
277
|
+
"JOIN kg_triples t3 ON t2.object = t3.subject "
|
|
278
|
+
"WHERE t1.predicate=? LIMIT 50", (arg or "确权于",))
|
|
279
|
+
return [{"chain": r[0] + "→" + r[1] + "→" + r[2]} for r in cur.fetchall()]
|
|
280
|
+
if kind == "ns":
|
|
281
|
+
cur.execute("SELECT subject, predicate, object FROM kg_triples WHERE subject LIKE ? LIMIT 50", ((arg or "kernel") + "%",))
|
|
282
|
+
return [{"subject": r[0], "predicate": r[1], "object": r[2]} for r in cur.fetchall()]
|
|
283
|
+
if kind == "type":
|
|
284
|
+
cur.execute("SELECT etype, COUNT(*) FROM kg_entities GROUP BY etype ORDER BY COUNT(*) DESC")
|
|
285
|
+
return {t: c for t, c in cur.fetchall()}
|
|
286
|
+
if kind == "confidence":
|
|
287
|
+
buckets = {"S": 0, "A": 0, "B": 0, "C": 0}
|
|
288
|
+
for e in self.entries:
|
|
289
|
+
for lvl, v in CONF_LEVELS.items():
|
|
290
|
+
if abs(e["confidence"] - v) < 1e-9:
|
|
291
|
+
buckets[lvl] += 1
|
|
292
|
+
return buckets
|
|
293
|
+
if kind == "entity":
|
|
294
|
+
cur.execute("SELECT name, etype, namespace FROM kg_entities WHERE name = ?", (arg or "",))
|
|
295
|
+
r = cur.fetchone()
|
|
296
|
+
return {"name": r[0], "etype": r[1], "namespace": r[2]} if r else {}
|
|
297
|
+
raise ValueError("未知查询类型:%s" % kind)
|
|
298
|
+
finally:
|
|
299
|
+
conn.close()
|
|
300
|
+
|
|
301
|
+
# ---------- 算子 7:三维晶格索引(元类 × 命名空间 × 时间) ----------
|
|
302
|
+
def lattice(self, meta_class=None, namespace=None, since=None, until=None):
|
|
303
|
+
out = {}
|
|
304
|
+
for e in self.entries:
|
|
305
|
+
if meta_class and e["meta_class"] != meta_class:
|
|
306
|
+
continue
|
|
307
|
+
if namespace and not e["namespace"].startswith(namespace):
|
|
308
|
+
continue
|
|
309
|
+
if since and e["ts"] < since:
|
|
310
|
+
continue
|
|
311
|
+
if until and e["ts"] > until:
|
|
312
|
+
continue
|
|
313
|
+
out.setdefault(e["meta_class"], {}).setdefault(e["namespace"], []).append(e["key"])
|
|
314
|
+
return out
|
|
315
|
+
|
|
316
|
+
# ---------- 算子 8:意图分类器(规则版加权打分) ----------
|
|
317
|
+
def classify(self, question):
|
|
318
|
+
scores = {}
|
|
319
|
+
for intent, kws in INTENTS.items():
|
|
320
|
+
s = 0.0
|
|
321
|
+
for kw, w in kws:
|
|
322
|
+
if kw in question.lower():
|
|
323
|
+
s += w
|
|
324
|
+
if s > 0:
|
|
325
|
+
scores[intent] = round(s, 3)
|
|
326
|
+
ranked = sorted(scores.items(), key=lambda x: -x[1])
|
|
327
|
+
return ranked
|
|
328
|
+
|
|
329
|
+
# ---------- 算子 9:缺口登记 ----------
|
|
330
|
+
def register_gap(self, question):
|
|
331
|
+
idx = self._load()
|
|
332
|
+
idx["gaps"].append({"question": question, "ts": now(), "resolved": 0})
|
|
333
|
+
self._save()
|
|
334
|
+
return {"status": "registered", "total_gaps": len(idx["gaps"])}
|
|
335
|
+
|
|
336
|
+
def list_gaps(self):
|
|
337
|
+
return [g for g in self._load()["gaps"] if not g.get("resolved")]
|
|
338
|
+
|
|
339
|
+
# ---------- 算子 10:双通道装配 ----------
|
|
340
|
+
def assemble(self, task_query, budget=None):
|
|
341
|
+
budget = budget or max(TOKEN_BUDGET_STATIC, est_tokens(task_query) * 10)
|
|
342
|
+
audit = {"ts": now(), "task": task_query, "static": [], "dynamic": [], "dropped": 0}
|
|
343
|
+
# 通道 A:静态内核强制载入
|
|
344
|
+
static = [e for e in self.entries if e.get("static")]
|
|
345
|
+
used = sum(est_tokens(str(e["value"])) for e in static)
|
|
346
|
+
audit["static"] = [e["key"] for e in static]
|
|
347
|
+
# 通道 B:动态按需
|
|
348
|
+
hits = self.search(task_query, limit=20)
|
|
349
|
+
picked, seen = [], set()
|
|
350
|
+
cap = budget * DYNAMIC_CAP
|
|
351
|
+
for h in hits:
|
|
352
|
+
t = est_tokens(h["value"])
|
|
353
|
+
if used + t > budget:
|
|
354
|
+
audit["dropped"] += 1
|
|
355
|
+
continue
|
|
356
|
+
if used + t > budget - (budget - cap) and used + t > budget:
|
|
357
|
+
audit["dropped"] += 1
|
|
358
|
+
continue
|
|
359
|
+
if h["key"] in seen:
|
|
360
|
+
continue
|
|
361
|
+
seen.add(h["key"])
|
|
362
|
+
picked.append(h)
|
|
363
|
+
used += t
|
|
364
|
+
audit["dynamic"] = [h["key"] for h in picked]
|
|
365
|
+
audit["used_tokens"] = used
|
|
366
|
+
audit["budget"] = budget
|
|
367
|
+
with open(self.audit_path, "a", encoding="utf-8") as f:
|
|
368
|
+
f.write(json.dumps(audit, ensure_ascii=False) + "\n")
|
|
369
|
+
return {"static": audit["static"], "dynamic": audit["dynamic"],
|
|
370
|
+
"used_tokens": used, "budget": budget, "dropped": audit["dropped"]}
|
|
371
|
+
|
|
372
|
+
# ---------- 算子 12:注册四步校验 ----------
|
|
373
|
+
def register(self, key, value, meta_class, namespace, tags=None):
|
|
374
|
+
"""metadata → index → graph → lock,缺一不落账。"""
|
|
375
|
+
steps = {}
|
|
376
|
+
# step 1 metadata
|
|
377
|
+
try:
|
|
378
|
+
r = self.add(key, value, meta_class, namespace, tags=tags, source="register")
|
|
379
|
+
steps["metadata"] = "ok" if r["status"] in ("ok", "duplicate") else r
|
|
380
|
+
except ValueError as ex:
|
|
381
|
+
steps["metadata"] = "FAIL: %s" % ex
|
|
382
|
+
return steps
|
|
383
|
+
# step 2 index
|
|
384
|
+
found = any(e["key"] == key for e in self.entries)
|
|
385
|
+
steps["index"] = "ok" if found else "FAIL"
|
|
386
|
+
if not found:
|
|
387
|
+
return steps
|
|
388
|
+
# step 3 graph
|
|
389
|
+
stats = self.build_graph()
|
|
390
|
+
steps["graph"] = "ok(triples=%d)" % stats["triples"]
|
|
391
|
+
# step 4 lock
|
|
392
|
+
e = next(x for x in self.entries if x["key"] == key)
|
|
393
|
+
self._load().setdefault("locked", []).append({"key": key, "sha": e["sha"], "ts": now()})
|
|
394
|
+
self._save()
|
|
395
|
+
steps["lock"] = "ok"
|
|
396
|
+
return steps
|
|
397
|
+
|
|
398
|
+
# ---------- 自检 ----------
|
|
399
|
+
def selftest(self):
|
|
400
|
+
import tempfile
|
|
401
|
+
results = []
|
|
402
|
+
def check(name, cond):
|
|
403
|
+
results.append((name, bool(cond)))
|
|
404
|
+
with tempfile.TemporaryDirectory() as td:
|
|
405
|
+
kr = KnowledgeRetriever(home=td)
|
|
406
|
+
# 1 条目模型与落盘
|
|
407
|
+
r = kr.add("truth.demo.001", "检索引擎结论:纯标准库路线可行", "决策", "kernel.demo", tags=["检索", "标准库"])
|
|
408
|
+
check("add_ok", r["status"] == "ok")
|
|
409
|
+
# 3 元类校验
|
|
410
|
+
try:
|
|
411
|
+
kr.add("bad.1", "x", "未知类", "kernel.demo")
|
|
412
|
+
check("meta_class_reject", False)
|
|
413
|
+
except ValueError:
|
|
414
|
+
check("meta_class_reject", True)
|
|
415
|
+
# 11 平移复用铁律
|
|
416
|
+
try:
|
|
417
|
+
kr.add("truth.copy.001", "检索引擎结论:纯标准库路线可行", "决策", "kernel.other")
|
|
418
|
+
check("reuse_no_redo", False)
|
|
419
|
+
except ValueError:
|
|
420
|
+
check("reuse_no_redo", True)
|
|
421
|
+
# 2 全文检索
|
|
422
|
+
kr.add("truth.demo.002", "向量语义检索需要 embedding 模型", "方法", "kernel.demo", tags=["向量"])
|
|
423
|
+
hits = kr.search("标准库")
|
|
424
|
+
check("search_hit", len(hits) >= 1 and hits[0]["key"] == "truth.demo.001")
|
|
425
|
+
miss = kr.search("完全不存在的词组xyzq")
|
|
426
|
+
check("search_no_fabricate", miss == [])
|
|
427
|
+
# 3 元类过滤
|
|
428
|
+
hits2 = kr.search("检索", meta_class="方法")
|
|
429
|
+
check("meta_filter", all(True for _ in hits2) and len(hits2) == 1)
|
|
430
|
+
# 4 关联推荐与标签聚类
|
|
431
|
+
kr.add("truth.demo.003", "图谱构建走规则驱动零成本路线", "方法", "kernel.demo", tags=["检索", "图谱"])
|
|
432
|
+
rel = kr.related("truth.demo.001")
|
|
433
|
+
check("related", any(x["key"] == "truth.demo.003" for x in rel))
|
|
434
|
+
tc = kr.tag_clusters()
|
|
435
|
+
check("tag_clusters", "检索" in tc and len(tc["检索"]) == 2)
|
|
436
|
+
# 6 图谱与多跳查询
|
|
437
|
+
kr.build_graph()
|
|
438
|
+
stats = kr.graph_query("stats")
|
|
439
|
+
check("graph_stats", stats["triples"] >= 4 and stats["entities"] >= 3)
|
|
440
|
+
check("graph_predicate", "确权于" in kr.graph_query("predicate"))
|
|
441
|
+
check("graph_2hop", isinstance(kr.graph_query("2hop"), list))
|
|
442
|
+
check("graph_3hop", isinstance(kr.graph_query("3hop"), list))
|
|
443
|
+
check("graph_type", "真值" in kr.graph_query("type"))
|
|
444
|
+
conf = kr.graph_query("confidence")
|
|
445
|
+
check("graph_confidence", conf["S"] + conf["A"] + conf["B"] + conf["C"] == len(kr.entries))
|
|
446
|
+
check("graph_entity", kr.graph_query("entity", "truth.demo.001")["etype"] == "真值")
|
|
447
|
+
# 7 晶格索引
|
|
448
|
+
lat = kr.lattice(meta_class="方法")
|
|
449
|
+
check("lattice", "kernel.demo" in lat.get("方法", {}))
|
|
450
|
+
# 8 意图分类器
|
|
451
|
+
c = kr.classify("图谱规模有多少三元组")
|
|
452
|
+
check("classify", c and c[0][0] == "stats")
|
|
453
|
+
# 9 缺口登记
|
|
454
|
+
kr.add("对外协议清单", "体系对外协议登记条目", "协议", "protocols.a")
|
|
455
|
+
kr.register_gap("体系目前有哪些对外协议")
|
|
456
|
+
check("gap_registered", len(kr.list_gaps()) == 1)
|
|
457
|
+
kr.build_graph()
|
|
458
|
+
check("gap_edge_generated", len(kr.list_gaps()) == 0)
|
|
459
|
+
# 10 双通道装配
|
|
460
|
+
kr.add("kernel.static.001", "META 公理:禁编造命中", "公理", "kernel.static", static=True)
|
|
461
|
+
asm = kr.assemble("标准库 检索")
|
|
462
|
+
check("assemble_static", "kernel.static.001" in asm["static"])
|
|
463
|
+
check("assemble_budget", asm["used_tokens"] <= asm["budget"])
|
|
464
|
+
# 12 注册四步
|
|
465
|
+
steps = kr.register("truth.demo.004", "注册四步全通验证", "协议", "kernel.demo")
|
|
466
|
+
check("register_four_steps", all(v == "ok" or v.startswith("ok") for v in steps.values()))
|
|
467
|
+
failed = [n for n, ok in results if not ok]
|
|
468
|
+
return results, failed
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def main(argv=None):
|
|
472
|
+
argv = argv or sys.argv[1:]
|
|
473
|
+
if argv and argv[0] == "selftest":
|
|
474
|
+
results, failed = KnowledgeRetriever().selftest()
|
|
475
|
+
for n, ok in results:
|
|
476
|
+
print(("PASS" if ok else "FAIL"), n)
|
|
477
|
+
print("total=%d failed=%d" % (len(results), len(failed)))
|
|
478
|
+
return 1 if failed else 0
|
|
479
|
+
p = argparse.ArgumentParser(prog="knowledge-retriever", description="检索知识算子包(纯标准库)")
|
|
480
|
+
sub = p.add_subparsers(dest="cmd")
|
|
481
|
+
s = sub.add_parser("add"); s.add_argument("key"); s.add_argument("value"); s.add_argument("meta_class"); s.add_argument("namespace"); s.add_argument("--tags", default=""); s.add_argument("--static", action="store_true")
|
|
482
|
+
s = sub.add_parser("search"); s.add_argument("query"); s.add_argument("--meta-class", dest="meta_class"); s.add_argument("--namespace"); s.add_argument("--limit", type=int, default=10)
|
|
483
|
+
s = sub.add_parser("related"); s.add_argument("key")
|
|
484
|
+
s = sub.add_parser("tags")
|
|
485
|
+
s = sub.add_parser("graph"); s.add_argument("kind"); s.add_argument("arg", nargs="?", default=None); s.add_argument("arg2", nargs="?", default=None)
|
|
486
|
+
s = sub.add_parser("lattice"); s.add_argument("--meta-class", dest="meta_class"); s.add_argument("--namespace")
|
|
487
|
+
s = sub.add_parser("classify"); s.add_argument("question")
|
|
488
|
+
s = sub.add_parser("gap"); s.add_argument("question", nargs="?")
|
|
489
|
+
s = sub.add_parser("assemble"); s.add_argument("task"); s.add_argument("--budget", type=int, default=None)
|
|
490
|
+
s = sub.add_parser("register"); s.add_argument("key"); s.add_argument("value"); s.add_argument("meta_class"); s.add_argument("namespace"); s.add_argument("--tags", default="")
|
|
491
|
+
a = p.parse_args(argv)
|
|
492
|
+
kr = KnowledgeRetriever()
|
|
493
|
+
out = None
|
|
494
|
+
if a.cmd == "add":
|
|
495
|
+
out = kr.add(a.key, a.value, a.meta_class, a.namespace, tags=[t for t in a.tags.split(",") if t], static=a.static)
|
|
496
|
+
elif a.cmd == "search":
|
|
497
|
+
out = kr.search(a.query, meta_class=a.meta_class, namespace=a.namespace, limit=a.limit)
|
|
498
|
+
if not out:
|
|
499
|
+
kr.register_gap(a.query)
|
|
500
|
+
out = [{"note": "未命中,已登记知识缺口"}]
|
|
501
|
+
elif a.cmd == "related":
|
|
502
|
+
out = kr.related(a.key)
|
|
503
|
+
elif a.cmd == "tags":
|
|
504
|
+
out = kr.tag_clusters()
|
|
505
|
+
elif a.cmd == "graph":
|
|
506
|
+
out = kr.graph_query(a.kind, a.arg, a.arg2)
|
|
507
|
+
elif a.cmd == "lattice":
|
|
508
|
+
out = kr.lattice(meta_class=a.meta_class, namespace=a.namespace)
|
|
509
|
+
elif a.cmd == "classify":
|
|
510
|
+
out = dict(kr.classify(a.question))
|
|
511
|
+
elif a.cmd == "gap":
|
|
512
|
+
out = kr.register_gap(a.question) if a.question else kr.list_gaps()
|
|
513
|
+
elif a.cmd == "assemble":
|
|
514
|
+
out = kr.assemble(a.task, budget=a.budget)
|
|
515
|
+
elif a.cmd == "register":
|
|
516
|
+
out = kr.register(a.key, a.value, a.meta_class, a.namespace, tags=[t for t in a.tags.split(",") if t])
|
|
517
|
+
else:
|
|
518
|
+
p.print_help()
|
|
519
|
+
return 2
|
|
520
|
+
print(json.dumps(out, ensure_ascii=False, indent=1))
|
|
521
|
+
return 0
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
if __name__ == "__main__":
|
|
525
|
+
sys.exit(main())
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "knowledge-retriever"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "检索知识算子包:全文检索/九大元类/图谱多跳/双通道装配/缺口登记,纯标准库单文件 | Knowledge retrieval operator pack (pure stdlib, single file)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
authors = [{ name = "tanbopiao" }]
|
|
13
|
+
keywords = ["knowledge", "retrieval", "knowledge-graph", "rag", "agent"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: Apache Software License",
|
|
17
|
+
"Topic :: Text Processing :: Indexing",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://www.huodouai.com/whitepaper/knowledge-retriever-whitepaper.html"
|
|
22
|
+
Repository = "https://github.com/tanbopiao/knowledge-retriever"
|
|
23
|
+
|
|
24
|
+
[project.scripts]
|
|
25
|
+
knowledge-retriever = "knowledge_retriever:main"
|
|
26
|
+
|
|
27
|
+
[tool.setuptools]
|
|
28
|
+
py-modules = ["knowledge_retriever"]
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""knowledge-retriever 自检:覆盖 12 项第一圈算子+边界声明用例。"""
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
import tempfile
|
|
7
|
+
import unittest
|
|
8
|
+
|
|
9
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
|
10
|
+
from knowledge_retriever import KnowledgeRetriever, est_tokens, tokenize, sha256 # noqa: E402
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class TestKnowledgeRetriever(unittest.TestCase):
|
|
14
|
+
def setUp(self):
|
|
15
|
+
self.td = tempfile.TemporaryDirectory()
|
|
16
|
+
self.kr = KnowledgeRetriever(home=self.td.name)
|
|
17
|
+
|
|
18
|
+
def tearDown(self):
|
|
19
|
+
self.td.cleanup()
|
|
20
|
+
|
|
21
|
+
def test_01_entry_model(self):
|
|
22
|
+
r = self.kr.add("t.1", "结论:纯标准库路线可行", "决策", "kernel.demo", tags=["a"])
|
|
23
|
+
self.assertEqual(r["status"], "ok")
|
|
24
|
+
self.assertIn("sha", r)
|
|
25
|
+
|
|
26
|
+
def test_02_meta_class_required(self):
|
|
27
|
+
with self.assertRaises(ValueError):
|
|
28
|
+
self.kr.add("t.2", "x", "未知类", "kernel.demo")
|
|
29
|
+
with self.assertRaises(ValueError):
|
|
30
|
+
self.kr.add("t.3", "x", "决策", "")
|
|
31
|
+
|
|
32
|
+
def test_03_reuse_no_redo(self):
|
|
33
|
+
self.kr.add("t.1", "同一段真值文本", "决策", "kernel.a")
|
|
34
|
+
with self.assertRaises(ValueError):
|
|
35
|
+
self.kr.add("t.copy", "同一段真值文本", "决策", "kernel.b")
|
|
36
|
+
r = self.kr.add("t.1", "同一段真值文本", "决策", "kernel.a")
|
|
37
|
+
self.assertEqual(r["status"], "duplicate")
|
|
38
|
+
|
|
39
|
+
def test_04_search_hit_and_no_fabricate(self):
|
|
40
|
+
self.kr.add("t.1", "向量语义检索需要 embedding", "方法", "kernel.a")
|
|
41
|
+
self.assertEqual(len(self.kr.search("embedding")), 1)
|
|
42
|
+
self.assertEqual(self.kr.search("完全不存在的词组xyzq"), [])
|
|
43
|
+
|
|
44
|
+
def test_05_meta_filter_and_confidence(self):
|
|
45
|
+
self.kr.add("t.a", "方法条目内容较长一些", "方法", "kernel.a")
|
|
46
|
+
self.kr.add("t.b", "风险条目内容", "风险", "kernel.a")
|
|
47
|
+
hits = self.kr.search("条目", meta_class="方法")
|
|
48
|
+
self.assertEqual(len(hits), 1)
|
|
49
|
+
self.assertEqual(hits[0]["meta_class"], "方法")
|
|
50
|
+
conf = self.kr.graph_query("confidence")
|
|
51
|
+
self.assertEqual(conf["S"] + conf["A"] + conf["B"] + conf["C"], 2)
|
|
52
|
+
|
|
53
|
+
def test_06_namespace_prefix_filter(self):
|
|
54
|
+
self.kr.add("t.a", "内核命名空间条目", "数据", "kernel.a")
|
|
55
|
+
self.kr.add("t.b", "协议命名空间条目", "协议", "protocols.a")
|
|
56
|
+
hits = self.kr.search("命名空间条目", namespace="protocols")
|
|
57
|
+
self.assertEqual(len(hits), 1)
|
|
58
|
+
self.assertEqual(hits[0]["namespace"], "protocols.a")
|
|
59
|
+
|
|
60
|
+
def test_07_related_and_clusters(self):
|
|
61
|
+
self.kr.add("t.1", "检索引擎条目一", "方法", "kernel.a", tags=["检索", "图谱"])
|
|
62
|
+
self.kr.add("t.2", "检索引擎条目二", "方法", "kernel.a", tags=["检索"])
|
|
63
|
+
rel = self.kr.related("t.1")
|
|
64
|
+
self.assertTrue(any(x["key"] == "t.2" and x["tag_overlap"] >= 1 for x in rel))
|
|
65
|
+
tc = self.kr.tag_clusters()
|
|
66
|
+
self.assertEqual(tc["检索"], ["t.1", "t.2"])
|
|
67
|
+
|
|
68
|
+
def test_08_graph_build_and_stats(self):
|
|
69
|
+
self.kr.add("t.1", "部署于:hub 节点。结论:图谱零成本可行", "决策", "kernel.a", tags=["图谱"])
|
|
70
|
+
stats = self.kr.build_graph()
|
|
71
|
+
self.assertGreaterEqual(stats["triples"], 4)
|
|
72
|
+
self.assertGreaterEqual(stats["entities"], 3)
|
|
73
|
+
|
|
74
|
+
def test_09_graph_multihop(self):
|
|
75
|
+
self.kr.add("t.1", "多跳查询样例", "决策", "kernel.a", tags=["x"])
|
|
76
|
+
self.kr.build_graph()
|
|
77
|
+
self.assertIsInstance(self.kr.graph_query("2hop"), list)
|
|
78
|
+
self.assertIsInstance(self.kr.graph_query("3hop"), list)
|
|
79
|
+
self.assertIn("确权于", self.kr.graph_query("predicate"))
|
|
80
|
+
self.assertIn("真值", self.kr.graph_query("type"))
|
|
81
|
+
self.assertEqual(self.kr.graph_query("entity", "t.1")["etype"], "真值")
|
|
82
|
+
self.assertIsInstance(self.kr.graph_query("ns", "kernel"), list)
|
|
83
|
+
|
|
84
|
+
def test_10_deploy_and_conclusion_extraction(self):
|
|
85
|
+
self.kr.add("t.1", "部署于:hub 节点。结论:抽取成功", "决策", "kernel.a")
|
|
86
|
+
self.kr.build_graph()
|
|
87
|
+
preds = self.kr.graph_query("predicate")
|
|
88
|
+
self.assertIn("部署于", preds)
|
|
89
|
+
self.assertIn("结论", preds)
|
|
90
|
+
|
|
91
|
+
def test_11_lattice(self):
|
|
92
|
+
self.kr.add("t.a", "晶格索引条目甲", "方法", "kernel.a")
|
|
93
|
+
self.kr.add("t.b", "晶格索引条目乙", "决策", "protocols.b")
|
|
94
|
+
lat = self.kr.lattice(meta_class="方法")
|
|
95
|
+
self.assertIn("kernel.a", lat.get("方法", {}))
|
|
96
|
+
lat2 = self.kr.lattice(namespace="protocols")
|
|
97
|
+
self.assertNotIn("方法", lat2)
|
|
98
|
+
|
|
99
|
+
def test_12_classify(self):
|
|
100
|
+
c = self.kr.classify("图谱规模有多少三元组")
|
|
101
|
+
self.assertTrue(c and c[0][0] == "stats")
|
|
102
|
+
c2 = self.kr.classify("谁确权这个组件")
|
|
103
|
+
self.assertTrue(c2 and c2[0][0] == "2hop")
|
|
104
|
+
|
|
105
|
+
def test_13_gap_registration(self):
|
|
106
|
+
self.kr.add("对外协议清单", "体系对外协议登记条目", "协议", "protocols.a")
|
|
107
|
+
self.kr.register_gap("体系目前有哪些对外协议")
|
|
108
|
+
self.assertEqual(len(self.kr.list_gaps()), 1)
|
|
109
|
+
self.kr.build_graph()
|
|
110
|
+
self.assertEqual(len(self.kr.list_gaps()), 0)
|
|
111
|
+
|
|
112
|
+
def test_14_assemble_dual_channel(self):
|
|
113
|
+
self.kr.add("s.1", "META 公理:禁编造命中", "公理", "kernel.static", static=True)
|
|
114
|
+
self.kr.add("t.1", "动态检索命中条目标准库", "数据", "kernel.a")
|
|
115
|
+
asm = self.kr.assemble("标准库 检索")
|
|
116
|
+
self.assertIn("s.1", asm["static"])
|
|
117
|
+
self.assertIn("t.1", asm["dynamic"])
|
|
118
|
+
self.assertLessEqual(asm["used_tokens"], asm["budget"])
|
|
119
|
+
self.assertTrue(os.path.exists(self.kr.audit_path))
|
|
120
|
+
|
|
121
|
+
def test_15_assemble_budget_cap(self):
|
|
122
|
+
for i in range(30):
|
|
123
|
+
self.kr.add("t.%02d" % i, "动态预算截断测试条目%d" % i, "数据", "kernel.a", tags=["预算"])
|
|
124
|
+
asm = self.kr.assemble("预算", budget=100)
|
|
125
|
+
self.assertLessEqual(asm["used_tokens"], 100)
|
|
126
|
+
self.assertGreater(asm["dropped"], 0)
|
|
127
|
+
|
|
128
|
+
def test_16_register_four_steps(self):
|
|
129
|
+
steps = self.kr.register("t.reg", "注册四步全通验证", "协议", "kernel.a")
|
|
130
|
+
self.assertEqual(set(steps), {"metadata", "index", "graph", "lock"})
|
|
131
|
+
self.assertTrue(all(str(v).startswith("ok") for v in steps.values()))
|
|
132
|
+
locked = self.kr._load()["locked"]
|
|
133
|
+
self.assertEqual(len(locked), 1)
|
|
134
|
+
|
|
135
|
+
def test_17_register_reject_no_commit(self):
|
|
136
|
+
steps = self.kr.register("t.bad", "x", "非法类", "kernel.a")
|
|
137
|
+
self.assertIn("FAIL", steps["metadata"])
|
|
138
|
+
self.assertEqual(len(self.kr.entries), 0)
|
|
139
|
+
|
|
140
|
+
def test_18_token_estimation(self):
|
|
141
|
+
self.assertEqual(est_tokens("四个汉字"), 4)
|
|
142
|
+
self.assertEqual(est_tokens("abcd"), 1)
|
|
143
|
+
self.assertEqual(est_tokens(""), 0)
|
|
144
|
+
|
|
145
|
+
def test_19_tokenize(self):
|
|
146
|
+
toks = tokenize("Hello 世界")
|
|
147
|
+
self.assertIn("hello", toks)
|
|
148
|
+
self.assertIn("世", toks)
|
|
149
|
+
|
|
150
|
+
def test_20_selftest_builtin(self):
|
|
151
|
+
results, failed = KnowledgeRetriever().selftest()
|
|
152
|
+
self.assertEqual(failed, [], "内置自检有失败项:%s" % failed)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
if __name__ == "__main__":
|
|
156
|
+
unittest.main(verbosity=2)
|