黄同学的后端和 Agent 笔记开通
Agent 基础入门

6.3 项目推进:MiniAgent v0.5

黄同学约 4 分钟读完试读

项目线进度: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 章的原则:

试读到这里

试读 35%

后面还有约 1800 字,讲 「第二部分:手写最小 RAG 管线」「跑起来:两条路线同台对比」「动手实验」 等 4 节。

站内购买还没开放。在小红书「黄同学」的店里买资料包,填订单号就能开通,开通后一直能看。