pytreesearch 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.
@@ -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,258 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytreesearch
3
+ Version: 0.1.0
4
+ Summary: Structure-aware document retrieval without embeddings.
5
+ Author-email: XuMing <xuming624@qq.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/shibing624/TreeSearch
8
+ Project-URL: Repository, https://github.com/shibing624/TreeSearch
9
+ Project-URL: Issues, https://github.com/shibing624/TreeSearch/issues
10
+ Keywords: rag,retrieval,tree-search,best-first,mcts,llm,bm25,document-indexing
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Text Processing :: Indexing
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: openai>=1.0
26
+ Requires-Dist: tiktoken>=0.5
27
+ Requires-Dist: python-dotenv>=1.0
28
+ Provides-Extra: cn
29
+ Requires-Dist: jieba>=0.42; extra == "cn"
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7.0; extra == "dev"
32
+ Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
33
+ Requires-Dist: jieba>=0.42; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # TreeSearch
37
+
38
+ **Structure-aware document retrieval without embeddings.**
39
+
40
+ No vector embeddings. No chunk splitting. BM25 + LLM reasoning over document tree structures.
41
+
42
+ [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/)
43
+ [![License](https://img.shields.io/badge/license-Apache%202.0-green.svg)](https://github.com/shibing624/TreeSearch/blob/main/LICENSE)
44
+ [![PyPI](https://img.shields.io/pypi/v/treesearch.svg)](https://pypi.org/project/treesearch/)
45
+
46
+ ## Why TreeSearch?
47
+
48
+ Traditional RAG systems split documents into fixed-size chunks and retrieve by vector similarity. This **destroys document structure**, loses heading hierarchy, and misses reasoning-dependent queries.
49
+
50
+ TreeSearch takes a fundamentally different approach — parse documents into **tree structures** based on their natural heading hierarchy, then use **BM25 + LLM reasoning** to navigate the tree and find the most relevant sections.
51
+
52
+ | | Traditional RAG | TreeSearch |
53
+ |---|---|---|
54
+ | **Preprocessing** | Chunk splitting + embedding | Parse headings → build tree |
55
+ | **Retrieval** | Vector similarity search | BM25 pre-scoring + LLM tree search |
56
+ | **Multi-doc** | Needs vector DB for routing | LLM routes by document descriptions |
57
+ | **Structure** | Lost after chunking | Fully preserved as tree hierarchy |
58
+ | **Dependencies** | Vector DB + embedding model | LLM only (no embedding, no vector DB) |
59
+ | **Zero-cost baseline** | N/A | BM25-only search (no LLM needed) |
60
+
61
+ ### Key Advantages
62
+
63
+ - **No vector embeddings** — No embedding model to train, deploy, or pay for
64
+ - **No chunk splitting** — Documents retain their natural heading structure
65
+ - **No vector DB** — No Pinecone, Milvus, or Chroma to manage
66
+ - **Tree-aware retrieval** — Heading hierarchy guides search, not arbitrary chunk boundaries
67
+ - **BM25 zero-cost baseline** — Instant keyword search with no API calls, useful as standalone or pre-filter
68
+ - **Budget-controlled LLM calls** — Set max LLM calls per query, with early stopping when confidence is high
69
+
70
+ ## Features
71
+
72
+ - **Three-layer search** — BM25 pre-scoring → Best-First tree search → LLM relevance evaluation
73
+ - **Tree-structured indexing** — Markdown and plain text documents are parsed into hierarchical trees
74
+ - **BM25 node-level index** — Structure-aware scoring with hierarchical field weighting (title > summary > body) and ancestor propagation
75
+ - **Best-First search** (default) — Priority queue driven, deterministic, with early stopping and budget control
76
+ - **MCTS search** — Monte Carlo Tree Search with LLM as value function
77
+ - **LLM single-pass** — One LLM call per document for minimal cost
78
+ - **Multi-document search** — Route queries across document collections via LLM reasoning
79
+ - **Chinese + English** — jieba tokenization for Chinese, regex for English (jieba is optional)
80
+ - **Batch indexing** — `build_index()` supports glob patterns for concurrent multi-file processing
81
+ - **Evaluation metrics** — Built-in Precision@K, Recall@K, MRR, NDCG@K, Hit@K, F1@K
82
+ - **Async-first** — All core functions are async with sync wrappers available
83
+ - **CLI included** — `treesearch index` and `treesearch search` commands
84
+
85
+ ## Installation
86
+
87
+ ```bash
88
+ pip install treesearch
89
+ ```
90
+
91
+ With Chinese support:
92
+ ```bash
93
+ pip install "treesearch[cn]"
94
+ ```
95
+
96
+ From source:
97
+
98
+ ```bash
99
+ git clone https://github.com/shibing624/TreeSearch.git
100
+ cd TreeSearch
101
+ pip install -e ".[dev]"
102
+ ```
103
+
104
+ ## Quick Start
105
+
106
+ ### 1. Set up API key
107
+
108
+ ```bash
109
+ export OPENAI_API_KEY="sk-..."
110
+ # Optional: custom endpoint
111
+ export OPENAI_BASE_URL="https://your-endpoint/v1"
112
+ ```
113
+
114
+ ### 2. Build index and search
115
+
116
+ ```python
117
+ import asyncio
118
+ from treesearch import build_index, load_index, Document, search
119
+
120
+ async def main():
121
+ # Build indexes for multiple files (supports glob patterns)
122
+ await build_index(
123
+ paths=["docs/*.md"],
124
+ output_dir="./indexes",
125
+ if_add_doc_description=True,
126
+ )
127
+
128
+ # Load indexed documents
129
+ import os
130
+ documents = []
131
+ for fp in sorted(os.listdir("./indexes")):
132
+ if not fp.endswith(".json"):
133
+ continue
134
+ data = load_index(os.path.join("./indexes", fp))
135
+ documents.append(Document(
136
+ doc_id=fp,
137
+ doc_name=data["doc_name"],
138
+ structure=data["structure"],
139
+ doc_description=data.get("doc_description", ""),
140
+ ))
141
+
142
+ # Search with Best-First strategy (default: BM25 + LLM)
143
+ result = await search(
144
+ query="How does the authentication system work?",
145
+ documents=documents,
146
+ )
147
+
148
+ for doc_result in result.documents:
149
+ for node in doc_result["nodes"]:
150
+ print(f"[{node['score']:.2f}] {node['title']}")
151
+ print(f" {node.get('text', '')[:200]}")
152
+
153
+ asyncio.run(main())
154
+ ```
155
+
156
+ ### 3. BM25 standalone (no LLM needed)
157
+
158
+ ```python
159
+ from treesearch import NodeBM25Index, Document, load_index
160
+
161
+ # Load documents
162
+ data = load_index("indexes/my_doc.json")
163
+ doc = Document(doc_id="doc1", doc_name=data["doc_name"], structure=data["structure"])
164
+
165
+ # BM25 node-level search — instant results, no API key needed
166
+ index = NodeBM25Index([doc])
167
+ results = index.search("authentication config", top_k=5)
168
+ for r in results:
169
+ print(f"[{r['bm25_score']:.4f}] {r['title']}")
170
+ ```
171
+
172
+ ### CLI Usage
173
+
174
+ ```bash
175
+ # Build indexes from glob pattern
176
+ treesearch index --paths "docs/*.md" --add-description
177
+
178
+ # Build index from specific files
179
+ treesearch index --paths doc1.md doc2.txt -o ./indexes
180
+
181
+ # Search with Best-First (default, BM25 + LLM)
182
+ treesearch search --index_dir ./indexes/ --query "How does auth work?"
183
+
184
+ # Search with MCTS strategy
185
+ treesearch search --index_dir ./indexes/ --query "deployment" --strategy mcts
186
+
187
+ # Search without BM25 pre-scoring
188
+ treesearch search --index_dir ./indexes/ --query "config" --no-bm25
189
+
190
+ # Control LLM budget
191
+ treesearch search --index_dir ./indexes/ --query "auth" --max-llm-calls 10
192
+ ```
193
+
194
+ ## How It Works
195
+
196
+ ```
197
+ Input Documents (MD/TXT)
198
+
199
+
200
+ ┌──────────┐
201
+ │ Indexer │ Parse headings → build tree → generate summaries
202
+ └────┬─────┘ (build_index supports glob for batch processing)
203
+ │ JSON index files
204
+
205
+ ┌──────────┐
206
+ │ search │ BM25 pre-score → route to docs → tree search
207
+ └────┬─────┘
208
+ │ SearchResult
209
+
210
+ Ranked nodes with scores and text
211
+ ```
212
+
213
+ **Layer 1 — BM25 Pre-Scoring**: `NodeBM25Index` scores all tree nodes using structure-aware BM25 with hierarchical field weighting (title > summary > body) and ancestor score propagation. Instant, no LLM needed.
214
+
215
+ **Layer 2 — Best-First Tree Search**: `BestFirstTreeSearch` uses a priority queue to expand the most promising nodes. LLM evaluates each node's relevance (title + summary only). Early stopping when top score drops below threshold.
216
+
217
+ **Layer 3 — Results**: Budget-controlled LLM calls with subtree caching for reuse across similar queries.
218
+
219
+ ### Search Strategies
220
+
221
+ | Strategy | Description | LLM Calls | Best For |
222
+ |----------|-------------|-----------|----------|
223
+ | `best_first` (default) | BM25 pre-scoring + priority queue + LLM evaluation | Moderate (budget-controlled) | General-purpose, best accuracy |
224
+ | `mcts` | Monte Carlo Tree Search with LLM as value function | High | Complex reasoning queries |
225
+ | `llm` | Single LLM call per document | Minimal | Low-cost, simple queries |
226
+ | BM25-only | `NodeBM25Index.search()` standalone | Zero | Instant keyword search, no API key |
227
+
228
+ ## Examples
229
+
230
+ | Example | Description |
231
+ |---------|-------------|
232
+ | [`01_index_and_search.py`](examples/01_index_and_search.py) | Single document indexing + BestFirst search |
233
+ | [`02_text_indexing.py`](examples/02_text_indexing.py) | Plain text → tree index with auto heading detection |
234
+ | [`03_cli_workflow.py`](examples/03_cli_workflow.py) | CLI workflow: build indexes + search with strategies |
235
+ | [`04_multi_doc_search.py`](examples/04_multi_doc_search.py) | Multi-doc BM25 + BestFirst + strategy comparison + Chinese |
236
+ | [`05_benchmark.py`](examples/05_benchmark.py) | Benchmark: BM25 / BestFirst / MCTS / LLM with metrics |
237
+
238
+ ## Project Structure
239
+
240
+ ```
241
+ treesearch/
242
+ ├── llm.py # Async LLM client with retry and JSON extraction
243
+ ├── tree.py # Document dataclass, tree operations, persistence
244
+ ├── indexer.py # Markdown / plain text → tree structure, batch build_index()
245
+ ├── search.py # Best-First, MCTS, LLM search, document routing, unified search() API
246
+ ├── rank_bm25.py # BM25Okapi, NodeBM25Index, Chinese/English tokenizer
247
+ ├── metrics.py # Evaluation: Precision@K, Recall@K, MRR, NDCG@K, Hit@K, F1@K
248
+ └── cli.py # CLI entry point (index / search)
249
+ ```
250
+
251
+ ## Documentation
252
+
253
+ - [Architecture](https://github.com/shibing624/TreeSearch/blob/main/docs/architecture.md) — Design principles and three-layer architecture
254
+ - [API Reference](https://github.com/shibing624/TreeSearch/blob/main/docs/api.md) — Complete API documentation
255
+
256
+ ## License
257
+
258
+ Apache License 2.0. See [LICENSE](https://github.com/shibing624/TreeSearch/blob/main/LICENSE) for details.
@@ -0,0 +1,223 @@
1
+ # TreeSearch
2
+
3
+ **Structure-aware document retrieval without embeddings.**
4
+
5
+ No vector embeddings. No chunk splitting. BM25 + LLM reasoning over document tree structures.
6
+
7
+ [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/)
8
+ [![License](https://img.shields.io/badge/license-Apache%202.0-green.svg)](https://github.com/shibing624/TreeSearch/blob/main/LICENSE)
9
+ [![PyPI](https://img.shields.io/pypi/v/treesearch.svg)](https://pypi.org/project/treesearch/)
10
+
11
+ ## Why TreeSearch?
12
+
13
+ Traditional RAG systems split documents into fixed-size chunks and retrieve by vector similarity. This **destroys document structure**, loses heading hierarchy, and misses reasoning-dependent queries.
14
+
15
+ TreeSearch takes a fundamentally different approach — parse documents into **tree structures** based on their natural heading hierarchy, then use **BM25 + LLM reasoning** to navigate the tree and find the most relevant sections.
16
+
17
+ | | Traditional RAG | TreeSearch |
18
+ |---|---|---|
19
+ | **Preprocessing** | Chunk splitting + embedding | Parse headings → build tree |
20
+ | **Retrieval** | Vector similarity search | BM25 pre-scoring + LLM tree search |
21
+ | **Multi-doc** | Needs vector DB for routing | LLM routes by document descriptions |
22
+ | **Structure** | Lost after chunking | Fully preserved as tree hierarchy |
23
+ | **Dependencies** | Vector DB + embedding model | LLM only (no embedding, no vector DB) |
24
+ | **Zero-cost baseline** | N/A | BM25-only search (no LLM needed) |
25
+
26
+ ### Key Advantages
27
+
28
+ - **No vector embeddings** — No embedding model to train, deploy, or pay for
29
+ - **No chunk splitting** — Documents retain their natural heading structure
30
+ - **No vector DB** — No Pinecone, Milvus, or Chroma to manage
31
+ - **Tree-aware retrieval** — Heading hierarchy guides search, not arbitrary chunk boundaries
32
+ - **BM25 zero-cost baseline** — Instant keyword search with no API calls, useful as standalone or pre-filter
33
+ - **Budget-controlled LLM calls** — Set max LLM calls per query, with early stopping when confidence is high
34
+
35
+ ## Features
36
+
37
+ - **Three-layer search** — BM25 pre-scoring → Best-First tree search → LLM relevance evaluation
38
+ - **Tree-structured indexing** — Markdown and plain text documents are parsed into hierarchical trees
39
+ - **BM25 node-level index** — Structure-aware scoring with hierarchical field weighting (title > summary > body) and ancestor propagation
40
+ - **Best-First search** (default) — Priority queue driven, deterministic, with early stopping and budget control
41
+ - **MCTS search** — Monte Carlo Tree Search with LLM as value function
42
+ - **LLM single-pass** — One LLM call per document for minimal cost
43
+ - **Multi-document search** — Route queries across document collections via LLM reasoning
44
+ - **Chinese + English** — jieba tokenization for Chinese, regex for English (jieba is optional)
45
+ - **Batch indexing** — `build_index()` supports glob patterns for concurrent multi-file processing
46
+ - **Evaluation metrics** — Built-in Precision@K, Recall@K, MRR, NDCG@K, Hit@K, F1@K
47
+ - **Async-first** — All core functions are async with sync wrappers available
48
+ - **CLI included** — `treesearch index` and `treesearch search` commands
49
+
50
+ ## Installation
51
+
52
+ ```bash
53
+ pip install treesearch
54
+ ```
55
+
56
+ With Chinese support:
57
+ ```bash
58
+ pip install "treesearch[cn]"
59
+ ```
60
+
61
+ From source:
62
+
63
+ ```bash
64
+ git clone https://github.com/shibing624/TreeSearch.git
65
+ cd TreeSearch
66
+ pip install -e ".[dev]"
67
+ ```
68
+
69
+ ## Quick Start
70
+
71
+ ### 1. Set up API key
72
+
73
+ ```bash
74
+ export OPENAI_API_KEY="sk-..."
75
+ # Optional: custom endpoint
76
+ export OPENAI_BASE_URL="https://your-endpoint/v1"
77
+ ```
78
+
79
+ ### 2. Build index and search
80
+
81
+ ```python
82
+ import asyncio
83
+ from treesearch import build_index, load_index, Document, search
84
+
85
+ async def main():
86
+ # Build indexes for multiple files (supports glob patterns)
87
+ await build_index(
88
+ paths=["docs/*.md"],
89
+ output_dir="./indexes",
90
+ if_add_doc_description=True,
91
+ )
92
+
93
+ # Load indexed documents
94
+ import os
95
+ documents = []
96
+ for fp in sorted(os.listdir("./indexes")):
97
+ if not fp.endswith(".json"):
98
+ continue
99
+ data = load_index(os.path.join("./indexes", fp))
100
+ documents.append(Document(
101
+ doc_id=fp,
102
+ doc_name=data["doc_name"],
103
+ structure=data["structure"],
104
+ doc_description=data.get("doc_description", ""),
105
+ ))
106
+
107
+ # Search with Best-First strategy (default: BM25 + LLM)
108
+ result = await search(
109
+ query="How does the authentication system work?",
110
+ documents=documents,
111
+ )
112
+
113
+ for doc_result in result.documents:
114
+ for node in doc_result["nodes"]:
115
+ print(f"[{node['score']:.2f}] {node['title']}")
116
+ print(f" {node.get('text', '')[:200]}")
117
+
118
+ asyncio.run(main())
119
+ ```
120
+
121
+ ### 3. BM25 standalone (no LLM needed)
122
+
123
+ ```python
124
+ from treesearch import NodeBM25Index, Document, load_index
125
+
126
+ # Load documents
127
+ data = load_index("indexes/my_doc.json")
128
+ doc = Document(doc_id="doc1", doc_name=data["doc_name"], structure=data["structure"])
129
+
130
+ # BM25 node-level search — instant results, no API key needed
131
+ index = NodeBM25Index([doc])
132
+ results = index.search("authentication config", top_k=5)
133
+ for r in results:
134
+ print(f"[{r['bm25_score']:.4f}] {r['title']}")
135
+ ```
136
+
137
+ ### CLI Usage
138
+
139
+ ```bash
140
+ # Build indexes from glob pattern
141
+ treesearch index --paths "docs/*.md" --add-description
142
+
143
+ # Build index from specific files
144
+ treesearch index --paths doc1.md doc2.txt -o ./indexes
145
+
146
+ # Search with Best-First (default, BM25 + LLM)
147
+ treesearch search --index_dir ./indexes/ --query "How does auth work?"
148
+
149
+ # Search with MCTS strategy
150
+ treesearch search --index_dir ./indexes/ --query "deployment" --strategy mcts
151
+
152
+ # Search without BM25 pre-scoring
153
+ treesearch search --index_dir ./indexes/ --query "config" --no-bm25
154
+
155
+ # Control LLM budget
156
+ treesearch search --index_dir ./indexes/ --query "auth" --max-llm-calls 10
157
+ ```
158
+
159
+ ## How It Works
160
+
161
+ ```
162
+ Input Documents (MD/TXT)
163
+
164
+
165
+ ┌──────────┐
166
+ │ Indexer │ Parse headings → build tree → generate summaries
167
+ └────┬─────┘ (build_index supports glob for batch processing)
168
+ │ JSON index files
169
+
170
+ ┌──────────┐
171
+ │ search │ BM25 pre-score → route to docs → tree search
172
+ └────┬─────┘
173
+ │ SearchResult
174
+
175
+ Ranked nodes with scores and text
176
+ ```
177
+
178
+ **Layer 1 — BM25 Pre-Scoring**: `NodeBM25Index` scores all tree nodes using structure-aware BM25 with hierarchical field weighting (title > summary > body) and ancestor score propagation. Instant, no LLM needed.
179
+
180
+ **Layer 2 — Best-First Tree Search**: `BestFirstTreeSearch` uses a priority queue to expand the most promising nodes. LLM evaluates each node's relevance (title + summary only). Early stopping when top score drops below threshold.
181
+
182
+ **Layer 3 — Results**: Budget-controlled LLM calls with subtree caching for reuse across similar queries.
183
+
184
+ ### Search Strategies
185
+
186
+ | Strategy | Description | LLM Calls | Best For |
187
+ |----------|-------------|-----------|----------|
188
+ | `best_first` (default) | BM25 pre-scoring + priority queue + LLM evaluation | Moderate (budget-controlled) | General-purpose, best accuracy |
189
+ | `mcts` | Monte Carlo Tree Search with LLM as value function | High | Complex reasoning queries |
190
+ | `llm` | Single LLM call per document | Minimal | Low-cost, simple queries |
191
+ | BM25-only | `NodeBM25Index.search()` standalone | Zero | Instant keyword search, no API key |
192
+
193
+ ## Examples
194
+
195
+ | Example | Description |
196
+ |---------|-------------|
197
+ | [`01_index_and_search.py`](examples/01_index_and_search.py) | Single document indexing + BestFirst search |
198
+ | [`02_text_indexing.py`](examples/02_text_indexing.py) | Plain text → tree index with auto heading detection |
199
+ | [`03_cli_workflow.py`](examples/03_cli_workflow.py) | CLI workflow: build indexes + search with strategies |
200
+ | [`04_multi_doc_search.py`](examples/04_multi_doc_search.py) | Multi-doc BM25 + BestFirst + strategy comparison + Chinese |
201
+ | [`05_benchmark.py`](examples/05_benchmark.py) | Benchmark: BM25 / BestFirst / MCTS / LLM with metrics |
202
+
203
+ ## Project Structure
204
+
205
+ ```
206
+ treesearch/
207
+ ├── llm.py # Async LLM client with retry and JSON extraction
208
+ ├── tree.py # Document dataclass, tree operations, persistence
209
+ ├── indexer.py # Markdown / plain text → tree structure, batch build_index()
210
+ ├── search.py # Best-First, MCTS, LLM search, document routing, unified search() API
211
+ ├── rank_bm25.py # BM25Okapi, NodeBM25Index, Chinese/English tokenizer
212
+ ├── metrics.py # Evaluation: Precision@K, Recall@K, MRR, NDCG@K, Hit@K, F1@K
213
+ └── cli.py # CLI entry point (index / search)
214
+ ```
215
+
216
+ ## Documentation
217
+
218
+ - [Architecture](https://github.com/shibing624/TreeSearch/blob/main/docs/architecture.md) — Design principles and three-layer architecture
219
+ - [API Reference](https://github.com/shibing624/TreeSearch/blob/main/docs/api.md) — Complete API documentation
220
+
221
+ ## License
222
+
223
+ Apache License 2.0. See [LICENSE](https://github.com/shibing624/TreeSearch/blob/main/LICENSE) for details.