kb_scoped.py
4.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""多知识库查询隔离:把 wiki 文件工具包一层路径硬边界 + 合并多库知识地图。
现状查询侧仅靠 prompt 叮嘱模型「别跨库串味」(软约束),模型物理上仍能读任意库文件。
本模块把 read/glob/grep 三个工具包成闭包:目标路径不在「本次所选库」的 wiki 根内直接拒绝,
模型即使想读别的库也读不到——隔离由代码强制,不依赖模型自觉。
"""
from __future__ import annotations
import os
from agentscope.message import TextBlock
from agentscope.tool import ToolResponse
from src.tools.wiki_tools import (
glob_wiki_files as _glob,
grep_wiki_files as _grep,
read_local_file as _read,
)
def _norm(p: str) -> str:
return str(p).replace("\\", "/").strip().lstrip("./")
def _tool_text(res: ToolResponse) -> str:
try:
first = res.content[0]
if isinstance(first, dict):
return str(first.get("text", ""))
return str(getattr(first, "text", ""))
except Exception:
return ""
def make_kb_scoped_tools(allowed_rels: list[str]):
"""据所选库 wiki 根相对路径列表,返回 (read_local_file, glob_wiki_files, grep_wiki_files) 三个受限工具。
返回函数的 __name__ 与原工具一致,保证 AgentScope 生成的工具名不变(prompt 里引用的名字有效)。
"""
# 空 allowed_rels(前端明确未选任何库)→ roots 保持空 → 一切路径越界拒绝,本次不检索任何库
roots = [r.rstrip("/") for r in (allowed_rels or []) if r]
def _allowed(p: str) -> bool:
q = _norm(p)
return any(q == r or q.startswith(r + "/") for r in roots)
def _deny(what: str) -> ToolResponse:
return ToolResponse(content=[TextBlock(
type="text",
text=f"❌ 越界拒绝:仅允许访问本次所选知识库目录 {roots},路径不在范围内:{what}",
)])
def read_local_file(file_path: str, start_line: int = 1, end_line: int = None) -> ToolResponse:
"""读取知识库页面内容(仅限本次所选知识库目录),支持指定行号范围局部读取。
参数:file_path 相对项目根的路径(须位于所选库的 wiki 根内);start_line/end_line 为 1 基行号。
"""
if not _allowed(file_path):
return _deny(file_path)
return _read(file_path, start_line, end_line)
def glob_wiki_files(pattern: str) -> ToolResponse:
"""按 Glob 通配符列出匹配的知识库文件(仅限本次所选知识库目录)。
参数:pattern 相对项目根的 glob(如 <库根>/**/*.md),须落在所选库根内。
"""
if not _allowed(pattern):
return _deny(pattern)
return _glob(pattern)
def grep_wiki_files(pattern: str, path_prefix: str = "") -> ToolResponse:
"""在所选知识库目录内做正则全文检索。
参数:pattern 正则;path_prefix 限定搜索的库根(省略时自动遍历全部所选库根并合并结果)。
"""
if path_prefix:
if not _allowed(path_prefix):
return _deny(path_prefix)
return _grep(pattern, path_prefix)
texts = []
for r in roots:
t = _tool_text(_grep(pattern, r))
if t and "未找到任何匹配" not in t and "目录不存在" not in t:
texts.append(t)
merged = "\n".join(texts) if texts else "未找到任何匹配的内容。"
return ToolResponse(content=[TextBlock(type="text", text=merged)])
return read_local_file, glob_wiki_files, grep_wiki_files
def load_kb_index_maps(kb_roots: list[dict]) -> str:
"""读取每个所选库的 index.md,按「库名 + 根目录」分段合并为知识库地图。
kb_roots: [{"name": 库名, "wiki_dir": 绝对目录, "wiki_rel": 项目根相对路径}]
"""
if not kb_roots:
return "(未选择任何知识库)"
parts = []
for r in kb_roots:
idx = os.path.join(r["wiki_dir"], "index.md")
try:
with open(idx, "r", encoding="utf-8", errors="replace") as f:
content = f.read().strip()
except Exception:
content = "(该库地图为空:index.md 不存在)"
parts.append(
f"### 知识库:{r['name']}(页面根目录:{r['wiki_rel']})\n{content}"
)
return "\n\n".join(parts)