tanze 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.
tanze-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zongyuanroot / tanbopiao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
tanze-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: tanze
3
+ Version: 0.1.0
4
+ Summary: 探赜 tanze — 轻量深研算子:规划→检索→成稿,纯标准库零依赖,内存几十 MB(提炼自 deer-flow 编排思路)
5
+ Author: tanbopiao
6
+ License: MIT
7
+ Project-URL: Homepage, https://gitcode.com/zongyuangen/tanze
8
+ Project-URL: Repository, https://github.com/tanbopiao/tanze
9
+ Keywords: agent,deep-research,llm,mcp,research-agent,yuanshu
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Topic :: Text Processing :: Indexing
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Dynamic: license-file
24
+
25
+ # tanze · 探赜
26
+
27
+ > 探赜索隐,钩深致远 ——《周易·系辞上》
28
+
29
+ 轻量深研算子:把一个公开可查的研究问题,走完「规划 → 检索 → 抓取 → 成稿」,
30
+ 产出带来源编号的 Markdown 报告。零第三方依赖(纯 Python 标准库),单进程运行,
31
+ 内存占用几十 MB 量级,提供脚本、MCP stdio 服务两种形态。
32
+
33
+ > **理念致谢**:编排思路提炼自 bytedance/deer-flow(MIT)的 Deep Research
34
+ > 多智能体设计;本仓库代码为独立重写的轻量化实现,与上游无代码血缘。
35
+
36
+ ## 为什么轻量复刻
37
+
38
+ deer-flow 完整形态需要 FastAPI 网关、Next.js 前端、Redis、无头浏览器与容器沙箱,
39
+ 内存 800MB–1.2GB。tanze 只保留其核心编排逻辑,全部由标准库实现:
40
+
41
+ | deer-flow 完整形态 | tanze 轻量复刻 |
42
+ | --- | --- |
43
+ | FastAPI 网关 + LangGraph 编排 | 单文件状态机,函数直调 |
44
+ | Next.js 前端 | 无界面,输出 Markdown |
45
+ | Redis 会话存储 | 无状态,一次一研 |
46
+ | Playwright 无头浏览器(250–500M/实例) | Bing 检索 + 按需正文抓取 |
47
+ | Docker 沙箱体系 | 复用宿主现有执行边界 |
48
+ | 内存 800M–1.2G | 实测峰值 22–24MB |
49
+
50
+ **复刻哲学**:功能可以复刻、架构可以复刻、逻辑可以复刻——代码算子由自己生成完善,
51
+ 达到同样的功能与能力,而资源占用降低一个数量级。
52
+
53
+ ## 用法
54
+
55
+ ```bash
56
+ export TANZE_LLM_KEY=<密钥,不入档>
57
+ python3 tanze.py --mem "研究问题"
58
+ ```
59
+
60
+ 环境变量:`TANZE_LLM_BASE`(默认 ModelScope 推理 API,任何 OpenAI 兼容接口均可)、
61
+ `TANZE_LLM_MODEL`、`TANZE_FETCH_LIMIT`(正文抓取页数上限,默认 3)。
62
+
63
+ ### MCP stdio 服务
64
+
65
+ ```bash
66
+ python3 mcp_server.py
67
+ ```
68
+
69
+ JSON-RPC 2.0 over stdio,工具 `research(question)`,任何 MCP 客户端可接。
70
+
71
+ ## 流程
72
+
73
+ 1. **plan**:问题拆成 3 个互补搜索查询(LLM,JSON;严禁年份开头,避免命中日历类页面);
74
+ 2. **search**:逐查询 Bing 中国检索,取标题、链接、摘要;
75
+ 3. **fetch**:按序抓取正文(去脚本样式,单页截断 4000 字符,总量受 `TANZE_FETCH_LIMIT` 约束);
76
+ 4. **report**:材料汇总成稿,只用材料内信息,不足处明确标注,引用带来源编号。
77
+
78
+ ## 边界
79
+
80
+ - 搜索依赖 Bing 中国页面结构(`b_algo` 结果块),结构变更时需适配;
81
+ - 正文抓取为单次拉取,无渲染引擎,动态页面拿不到的内容以摘要代替;
82
+ - 仅适合公开可查的事实题;私有概念、需登录的数据不适用;
83
+ - LLM 密钥经环境变量注入,不写入任何存储。
84
+
85
+ ## 许可
86
+
87
+ MIT。
tanze-0.1.0/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # tanze · 探赜
2
+
3
+ > 探赜索隐,钩深致远 ——《周易·系辞上》
4
+
5
+ 轻量深研算子:把一个公开可查的研究问题,走完「规划 → 检索 → 抓取 → 成稿」,
6
+ 产出带来源编号的 Markdown 报告。零第三方依赖(纯 Python 标准库),单进程运行,
7
+ 内存占用几十 MB 量级,提供脚本、MCP stdio 服务两种形态。
8
+
9
+ > **理念致谢**:编排思路提炼自 bytedance/deer-flow(MIT)的 Deep Research
10
+ > 多智能体设计;本仓库代码为独立重写的轻量化实现,与上游无代码血缘。
11
+
12
+ ## 为什么轻量复刻
13
+
14
+ deer-flow 完整形态需要 FastAPI 网关、Next.js 前端、Redis、无头浏览器与容器沙箱,
15
+ 内存 800MB–1.2GB。tanze 只保留其核心编排逻辑,全部由标准库实现:
16
+
17
+ | deer-flow 完整形态 | tanze 轻量复刻 |
18
+ | --- | --- |
19
+ | FastAPI 网关 + LangGraph 编排 | 单文件状态机,函数直调 |
20
+ | Next.js 前端 | 无界面,输出 Markdown |
21
+ | Redis 会话存储 | 无状态,一次一研 |
22
+ | Playwright 无头浏览器(250–500M/实例) | Bing 检索 + 按需正文抓取 |
23
+ | Docker 沙箱体系 | 复用宿主现有执行边界 |
24
+ | 内存 800M–1.2G | 实测峰值 22–24MB |
25
+
26
+ **复刻哲学**:功能可以复刻、架构可以复刻、逻辑可以复刻——代码算子由自己生成完善,
27
+ 达到同样的功能与能力,而资源占用降低一个数量级。
28
+
29
+ ## 用法
30
+
31
+ ```bash
32
+ export TANZE_LLM_KEY=<密钥,不入档>
33
+ python3 tanze.py --mem "研究问题"
34
+ ```
35
+
36
+ 环境变量:`TANZE_LLM_BASE`(默认 ModelScope 推理 API,任何 OpenAI 兼容接口均可)、
37
+ `TANZE_LLM_MODEL`、`TANZE_FETCH_LIMIT`(正文抓取页数上限,默认 3)。
38
+
39
+ ### MCP stdio 服务
40
+
41
+ ```bash
42
+ python3 mcp_server.py
43
+ ```
44
+
45
+ JSON-RPC 2.0 over stdio,工具 `research(question)`,任何 MCP 客户端可接。
46
+
47
+ ## 流程
48
+
49
+ 1. **plan**:问题拆成 3 个互补搜索查询(LLM,JSON;严禁年份开头,避免命中日历类页面);
50
+ 2. **search**:逐查询 Bing 中国检索,取标题、链接、摘要;
51
+ 3. **fetch**:按序抓取正文(去脚本样式,单页截断 4000 字符,总量受 `TANZE_FETCH_LIMIT` 约束);
52
+ 4. **report**:材料汇总成稿,只用材料内信息,不足处明确标注,引用带来源编号。
53
+
54
+ ## 边界
55
+
56
+ - 搜索依赖 Bing 中国页面结构(`b_algo` 结果块),结构变更时需适配;
57
+ - 正文抓取为单次拉取,无渲染引擎,动态页面拿不到的内容以摘要代替;
58
+ - 仅适合公开可查的事实题;私有概念、需登录的数据不适用;
59
+ - LLM 密钥经环境变量注入,不写入任何存储。
60
+
61
+ ## 许可
62
+
63
+ MIT。
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tanze"
7
+ version = "0.1.0"
8
+ description = "探赜 tanze — 轻量深研算子:规划→检索→成稿,纯标准库零依赖,内存几十 MB(提炼自 deer-flow 编排思路)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "tanbopiao" }]
13
+ keywords = ["agent", "deep-research", "llm", "mcp", "research-agent", "yuanshu"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
24
+ "Topic :: Text Processing :: Indexing",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://gitcode.com/zongyuangen/tanze"
29
+ Repository = "https://github.com/tanbopiao/tanze"
30
+
31
+ [project.scripts]
32
+ tanze = "tanze.__main__:main"
33
+ tanze-mcp = "tanze.mcp:main"
34
+
35
+ [tool.setuptools]
36
+ packages = ["tanze"]
tanze-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,19 @@
1
+ # -*- coding: utf-8 -*-
2
+ """探赜 tanze —— 轻量深研算子
3
+
4
+ 道统铭文:探赜索隐,钩深致远(《周易·系辞上》)
5
+ 提炼自 bytedance/deer-flow 的「规划→研究→成稿」编排思路,
6
+ 零第三方依赖(纯标准库),单进程内存占用为几十 MB 量级。
7
+ """
8
+ from .core import ( # noqa: F401
9
+ gather,
10
+ fetch_text,
11
+ llm,
12
+ mem_peak_mb,
13
+ plan,
14
+ report,
15
+ research,
16
+ search,
17
+ )
18
+
19
+ __version__ = "0.1.0"
@@ -0,0 +1,22 @@
1
+ # -*- coding: utf-8 -*-
2
+ """python -m tanze "研究问题" / tanze 命令行入口。"""
3
+ import sys
4
+
5
+ from . import core
6
+
7
+
8
+ def main() -> None:
9
+ args = [a for a in sys.argv[1:] if a != "--mem"]
10
+ show_mem = "--mem" in sys.argv
11
+ if not args:
12
+ print("用法: tanze \"研究问题\" (加 --mem 输出内存峰值)")
13
+ sys.exit(1)
14
+ result = core.research(" ".join(args))
15
+ print(result["report"])
16
+ print(f"\n--- 耗时 {result['elapsed']}s", file=sys.stderr)
17
+ if show_mem:
18
+ print(f"--- 内存峰值 {core.mem_peak_mb():.1f} MB", file=sys.stderr)
19
+
20
+
21
+ if __name__ == "__main__":
22
+ main()
@@ -0,0 +1,171 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """探赜 tanze —— 轻量深研算子
4
+
5
+ 道统铭文:探赜索隐,钩深致远(《周易·系辞上》)
6
+ 提炼自 bytedance/deer-flow 的「规划→研究→成稿」编排思路,
7
+ 零第三方依赖(纯标准库),单进程内存占用为几十 MB 量级。
8
+
9
+ 流程:plan(问题拆解)→ search(逐查询检索)→ fetch(正文抓取)
10
+ → report(综合成稿)。LLM 走 OpenAI 兼容接口。
11
+
12
+ 环境变量:
13
+ TANZE_LLM_BASE OpenAI 兼容接口地址(默认 ModelScope 推理 API)
14
+ TANZE_LLM_KEY API 密钥(不入档、不回显)
15
+ TANZE_LLM_MODEL 模型名
16
+ TANZE_FETCH_LIMIT 正文抓取页数上限(默认 3)
17
+
18
+ 用法:
19
+ python3 tanze.py "研究问题"
20
+ python3 tanze.py --mem "研究问题" # 结束时输出内存峰值
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import re
26
+ import resource
27
+ import sys
28
+ import time
29
+ import urllib.parse
30
+ import urllib.request
31
+
32
+ LLM_BASE = "https://api-inference.modelscope.cn/v1"
33
+ LLM_MODEL = "deepseek-ai/DeepSeek-V4.1-Flash-1017"
34
+ FETCH_LIMIT = 3
35
+ UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126 Safari/537.36"
36
+ TIMEOUT = 30
37
+
38
+
39
+ # ---------- 基础层 ----------
40
+
41
+ def _http(url: str, data: bytes | None = None, headers: dict | None = None) -> str:
42
+ req = urllib.request.Request(url, data=data, headers={"User-Agent": UA, **(headers or {})})
43
+ with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
44
+ return resp.read().decode("utf-8", "replace")
45
+
46
+
47
+ def llm(messages: list[dict], max_tokens: int = 2000) -> str:
48
+ import os
49
+ base = os.environ.get("TANZE_LLM_BASE", LLM_BASE).rstrip("/")
50
+ key = os.environ["TANZE_LLM_KEY"]
51
+ model = os.environ.get("TANZE_LLM_MODEL", LLM_MODEL)
52
+ body = json.dumps({"model": model, "messages": messages, "max_tokens": max_tokens,
53
+ "temperature": 0.3}).encode()
54
+ out = _http(f"{base}/chat/completions", body,
55
+ {"Authorization": f"Bearer {key}", "Content-Type": "application/json"})
56
+ return json.loads(out)["choices"][0]["message"]["content"]
57
+
58
+
59
+ # ---------- 搜索层 ----------
60
+
61
+ def search(query: str, top: int = 4) -> list[dict]:
62
+ """Bing 中国网页检索,返回 [{title,url,snippet}]。"""
63
+ html = _http("https://cn.bing.com/search?" + urllib.parse.urlencode({"q": query, "count": top}))
64
+ out, seen = [], set()
65
+ # 结果块:<li class="b_algo"> ... <h2><a href="URL">TITLE</a></h2> ... <p>SNIPPET</p>
66
+ for block in re.findall(r'<li class="b_algo".*?</li>', html, re.S)[:top * 2]:
67
+ m = re.search(r'<h2[^>]*><a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', block, re.S)
68
+ if not m:
69
+ continue
70
+ url, title = m.group(1), re.sub(r"<[^>]+>", "", m.group(2)).strip()
71
+ if url.startswith("http") and url not in seen:
72
+ snip = re.search(r"<p[^>]*>(.*?)</p>", block, re.S)
73
+ out.append({"title": title, "url": url,
74
+ "snippet": re.sub(r"<[^>]+>", "", snip.group(1)).strip() if snip else ""})
75
+ seen.add(url)
76
+ if len(out) >= top:
77
+ break
78
+ return out
79
+
80
+
81
+ def fetch_text(url: str, limit: int = 4000) -> str:
82
+ """抓取网页正文文本(去脚本样式,截断)。"""
83
+ try:
84
+ html = _http(url)
85
+ except Exception:
86
+ return ""
87
+ html = re.sub(r"<(script|style|noscript)[^>]*>.*?</\1>", " ", html, flags=re.S | re.I)
88
+ text = re.sub(r"<[^>]+>", " ", html)
89
+ text = re.sub(r"\s+", " ", text).strip()
90
+ return text[:limit]
91
+
92
+
93
+ # ---------- 编排层:plan → search → fetch → report ----------
94
+
95
+ def plan(question: str) -> list[str]:
96
+ raw = llm([{"role": "system", "content":
97
+ "把研究问题拆成 3 个具体的中文搜索查询。要求:每个查询是独立的搜索词组"
98
+ "(不是完整句子),必须包含具体技术名词或实体;"
99
+ "严禁以年份开头(如「2026 年…」),年份一律放查询末尾或省略,避免命中日历类页面。"
100
+ "只输出 JSON 字符串数组,例如:"
101
+ '["LangGraph CrewAI Agent 框架对比","MCP 协议 智能体 标准化","Deep Research 多智能体 实现"]。'},
102
+ {"role": "user", "content": question}], max_tokens=500)
103
+ m = re.search(r"\[.*\]", raw, re.S)
104
+ try:
105
+ queries = json.loads(m.group(0)) if m else []
106
+ except Exception:
107
+ queries = []
108
+ return [q for q in queries if isinstance(q, str) and q.strip()][:4] or [question]
109
+
110
+
111
+ def gather(question: str, queries: list[str]) -> list[dict]:
112
+ """检索并抓取正文,返回材料列表。"""
113
+ sources, fetched = [], 0
114
+ for q in queries:
115
+ for hit in search(q):
116
+ hit["query"] = q
117
+ sources.append(hit)
118
+ # 去重后按序抓正文,直到抓满 FETCH_LIMIT 页
119
+ for s in sources:
120
+ if fetched >= FETCH_LIMIT:
121
+ break
122
+ s["text"] = fetch_text(s["url"])
123
+ if len(s["text"]) > 500:
124
+ fetched += 1
125
+ else:
126
+ s["text"] = ""
127
+ time.sleep(0.3)
128
+ return sources
129
+
130
+
131
+ def report(question: str, sources: list[dict]) -> str:
132
+ material = "\n\n".join(
133
+ f"【来源{i+1}】{s['title']}({s['url']})\n{s['snippet']}\n{s.get('text', '')[:3000]}"
134
+ for i, s in enumerate([x for x in sources if x.get("text") or x["snippet"]][:8]))
135
+ return llm([{"role": "system", "content":
136
+ "你是深研报告员。基于给定材料写中文 Markdown 报告:"
137
+ "先给三行以内的核心结论,再分小节展开,末尾列要点清单。"
138
+ "只用材料中的信息,材料不足处明确标注「材料未覆盖」。引用来源用【来源N】。"},
139
+ {"role": "user", "content": f"研究问题:{question}\n\n材料:\n{material}"}],
140
+ max_tokens=3000)
141
+
142
+
143
+ def research(question: str, verbose: bool = True) -> dict:
144
+ t0 = time.time()
145
+ queries = plan(question)
146
+ if verbose:
147
+ print(f"[plan] {queries}", file=sys.stderr)
148
+ sources = gather(question, queries)
149
+ if verbose:
150
+ ok = sum(1 for s in sources if s.get("text"))
151
+ print(f"[search] {len(sources)} 条结果,{ok} 页正文入料", file=sys.stderr)
152
+ text = report(question, sources)
153
+ return {"question": question, "queries": queries, "sources": sources,
154
+ "report": text, "elapsed": round(time.time() - t0, 1)}
155
+
156
+
157
+ def mem_peak_mb() -> float:
158
+ return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024 # Linux: KB
159
+
160
+
161
+ if __name__ == "__main__":
162
+ args = [a for a in sys.argv[1:] if a != "--mem"]
163
+ show_mem = "--mem" in sys.argv
164
+ if not args:
165
+ print(__doc__)
166
+ sys.exit(1)
167
+ result = research(" ".join(args))
168
+ print(result["report"])
169
+ print(f"\n--- 耗时 {result['elapsed']}s", file=sys.stderr)
170
+ if show_mem:
171
+ print(f"--- 内存峰值 {mem_peak_mb():.1f} MB", file=sys.stderr)
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """tanze MCP 服务:JSON-RPC 2.0 over stdio(零依赖,照道统算子谱模式)。
4
+
5
+ 启动:python3 mcp_server.py
6
+ 工具:research(question) —— 深研一个问题,返回 Markdown 报告。
7
+
8
+ 密钥来源(按序尝试,均不回显不入档):
9
+ 1. 环境变量 TANZE_LLM_KEY / TANZE_LLM_BASE / TANZE_LLM_MODEL
10
+ 2. /opt/yuanshu/.secrets/llm.env(YUANSHU_LLM_* 字段)
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import sys
17
+
18
+ from . import core as tanze # noqa: F401
19
+
20
+
21
+ def _load_secrets() -> None:
22
+ if os.environ.get("TANZE_LLM_KEY"):
23
+ return
24
+ for path in ("/opt/yuanshu/.secrets/llm.env",):
25
+ try:
26
+ with open(path) as fh:
27
+ for line in fh:
28
+ line = line.strip()
29
+ if "=" not in line or line.startswith("#"):
30
+ continue
31
+ k, v = line.split("=", 1)
32
+ if k == "YUANSHU_LLM_KEY":
33
+ os.environ.setdefault("TANZE_LLM_KEY", v)
34
+ elif k == "YUANSHU_LLM_BASE":
35
+ os.environ.setdefault("TANZE_LLM_BASE", v)
36
+ elif k == "YUANSHU_LLM_MODEL":
37
+ os.environ.setdefault("TANZE_LLM_MODEL", v)
38
+ except OSError:
39
+ pass
40
+
41
+
42
+ TOOLS_META = {
43
+ "research": {
44
+ "desc": "探赜深研:把问题拆解为搜索查询,检索并抓取公开网页,综合成带来源的 Markdown 报告。适合前沿技术架构、安全治理等公开可查的事实题。",
45
+ "schema": {"type": "object",
46
+ "properties": {"question": {"type": "string", "description": "研究问题(公开可查的事实题)"}},
47
+ "required": ["question"]},
48
+ },
49
+ }
50
+
51
+
52
+ def tool_research(args: dict) -> dict:
53
+ question = str(args.get("question", "")).strip()
54
+ if not question:
55
+ return {"ok": False, "error": "question required"}
56
+ result = tanze.research(question, verbose=False)
57
+ return {"ok": True, "question": question, "queries": result["queries"],
58
+ "elapsed_s": result["elapsed"], "report": result["report"]}
59
+
60
+
61
+ DISPATCH = {"research": tool_research}
62
+
63
+
64
+ def handle(req: dict) -> dict | None:
65
+ method, rid = req.get("method"), req.get("id")
66
+ if method == "initialize":
67
+ return {"jsonrpc": "2.0", "id": rid, "result": {
68
+ "protocolVersion": "2024-11-05",
69
+ "capabilities": {"tools": {}},
70
+ "serverInfo": {"name": "tanze", "version": "0.1.0"}}}
71
+ if method == "tools/list":
72
+ return {"jsonrpc": "2.0", "id": rid, "result": {
73
+ "tools": [{"name": n, "description": m["desc"], "inputSchema": m["schema"]}
74
+ for n, m in TOOLS_META.items()]}}
75
+ if method == "tools/call":
76
+ params = req.get("params") or {}
77
+ name = params.get("name")
78
+ try:
79
+ out = DISPATCH[name](params.get("args") or {})
80
+ text = out.get("report") if out.get("ok") else json.dumps(out, ensure_ascii=False)
81
+ except Exception as exc: # 工具内异常转文本,不中断服务
82
+ text = f"research failed: {exc}"
83
+ return {"jsonrpc": "2.0", "id": rid, "result": {
84
+ "content": [{"type": "text", "text": text}]}}
85
+ if method == "notifications/initialized":
86
+ return None
87
+ if rid is not None:
88
+ return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": "method not found"}}
89
+ return None
90
+
91
+
92
+ def main() -> None:
93
+ _load_secrets()
94
+ for line in sys.stdin:
95
+ line = line.strip()
96
+ if not line:
97
+ continue
98
+ try:
99
+ req = json.loads(line)
100
+ except json.JSONDecodeError:
101
+ continue
102
+ resp = handle(req)
103
+ if resp is not None:
104
+ print(json.dumps(resp, ensure_ascii=False), flush=True)
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: tanze
3
+ Version: 0.1.0
4
+ Summary: 探赜 tanze — 轻量深研算子:规划→检索→成稿,纯标准库零依赖,内存几十 MB(提炼自 deer-flow 编排思路)
5
+ Author: tanbopiao
6
+ License: MIT
7
+ Project-URL: Homepage, https://gitcode.com/zongyuangen/tanze
8
+ Project-URL: Repository, https://github.com/tanbopiao/tanze
9
+ Keywords: agent,deep-research,llm,mcp,research-agent,yuanshu
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Topic :: Text Processing :: Indexing
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Dynamic: license-file
24
+
25
+ # tanze · 探赜
26
+
27
+ > 探赜索隐,钩深致远 ——《周易·系辞上》
28
+
29
+ 轻量深研算子:把一个公开可查的研究问题,走完「规划 → 检索 → 抓取 → 成稿」,
30
+ 产出带来源编号的 Markdown 报告。零第三方依赖(纯 Python 标准库),单进程运行,
31
+ 内存占用几十 MB 量级,提供脚本、MCP stdio 服务两种形态。
32
+
33
+ > **理念致谢**:编排思路提炼自 bytedance/deer-flow(MIT)的 Deep Research
34
+ > 多智能体设计;本仓库代码为独立重写的轻量化实现,与上游无代码血缘。
35
+
36
+ ## 为什么轻量复刻
37
+
38
+ deer-flow 完整形态需要 FastAPI 网关、Next.js 前端、Redis、无头浏览器与容器沙箱,
39
+ 内存 800MB–1.2GB。tanze 只保留其核心编排逻辑,全部由标准库实现:
40
+
41
+ | deer-flow 完整形态 | tanze 轻量复刻 |
42
+ | --- | --- |
43
+ | FastAPI 网关 + LangGraph 编排 | 单文件状态机,函数直调 |
44
+ | Next.js 前端 | 无界面,输出 Markdown |
45
+ | Redis 会话存储 | 无状态,一次一研 |
46
+ | Playwright 无头浏览器(250–500M/实例) | Bing 检索 + 按需正文抓取 |
47
+ | Docker 沙箱体系 | 复用宿主现有执行边界 |
48
+ | 内存 800M–1.2G | 实测峰值 22–24MB |
49
+
50
+ **复刻哲学**:功能可以复刻、架构可以复刻、逻辑可以复刻——代码算子由自己生成完善,
51
+ 达到同样的功能与能力,而资源占用降低一个数量级。
52
+
53
+ ## 用法
54
+
55
+ ```bash
56
+ export TANZE_LLM_KEY=<密钥,不入档>
57
+ python3 tanze.py --mem "研究问题"
58
+ ```
59
+
60
+ 环境变量:`TANZE_LLM_BASE`(默认 ModelScope 推理 API,任何 OpenAI 兼容接口均可)、
61
+ `TANZE_LLM_MODEL`、`TANZE_FETCH_LIMIT`(正文抓取页数上限,默认 3)。
62
+
63
+ ### MCP stdio 服务
64
+
65
+ ```bash
66
+ python3 mcp_server.py
67
+ ```
68
+
69
+ JSON-RPC 2.0 over stdio,工具 `research(question)`,任何 MCP 客户端可接。
70
+
71
+ ## 流程
72
+
73
+ 1. **plan**:问题拆成 3 个互补搜索查询(LLM,JSON;严禁年份开头,避免命中日历类页面);
74
+ 2. **search**:逐查询 Bing 中国检索,取标题、链接、摘要;
75
+ 3. **fetch**:按序抓取正文(去脚本样式,单页截断 4000 字符,总量受 `TANZE_FETCH_LIMIT` 约束);
76
+ 4. **report**:材料汇总成稿,只用材料内信息,不足处明确标注,引用带来源编号。
77
+
78
+ ## 边界
79
+
80
+ - 搜索依赖 Bing 中国页面结构(`b_algo` 结果块),结构变更时需适配;
81
+ - 正文抓取为单次拉取,无渲染引擎,动态页面拿不到的内容以摘要代替;
82
+ - 仅适合公开可查的事实题;私有概念、需登录的数据不适用;
83
+ - LLM 密钥经环境变量注入,不写入任何存储。
84
+
85
+ ## 许可
86
+
87
+ MIT。
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ tanze/__init__.py
5
+ tanze/__main__.py
6
+ tanze/core.py
7
+ tanze/mcp.py
8
+ tanze.egg-info/PKG-INFO
9
+ tanze.egg-info/SOURCES.txt
10
+ tanze.egg-info/dependency_links.txt
11
+ tanze.egg-info/entry_points.txt
12
+ tanze.egg-info/top_level.txt
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ tanze = tanze.__main__:main
3
+ tanze-mcp = tanze.mcp:main
@@ -0,0 +1 @@
1
+ tanze