6.3 项目推进:MiniAgent v0.5
项目线进度:v0.4 能跑长任务、能过夜,但在大代码库里只能靠猜文件名。本节升级到 v0.5:给 Agent 加
grep_code工具(它的主力检索),另写一个最小 RAG 管线 demo(rag_demo.py),把 6.1 的五步亲手走一遍。完整代码在miniagent/v05_search/。
第一部分:grep_code 工具
纯 Python 实现(不依赖系统 grep,跨平台)。参数里的 pattern 支持正则表达式:一种"带通配能力的搜索词"写法,比如 def test_ 匹配所有以它开头的行片段,total|price 匹配含其中任意一个词的行。现在只需要知道"普通的词直接写就是合法 pattern",正则的花活模型比你熟。核心逻辑:
python
def grep_code(pattern: str, directory: str = ".", file_glob: str = "*") -> str:
regex = re.compile(pattern)
hits = []
for path in sorted(Path(directory).rglob(file_glob)):
if not path.is_file() or any(p.startswith(".") for p in path.parts):
continue # 跳过隐藏目录(.git、.venv)
try:
lines = path.read_text().splitlines()
except (UnicodeDecodeError, OSError):
continue # 跳过二进制
for lineno, line in enumerate(lines, 1):
if regex.search(line):
hits.append(f"{path}:{lineno}: {line.strip()[:200]}")
if len(hits) >= 50:
hits.append("...(超过 50 条命中,请用更精确的 pattern)")
return "\n".join(hits)
return "\n".join(hits) if hits else "没有找到匹配"为"使用者是模型"做的三处设计,延续第 3 章的原则: