跳转至

构建文件与代码助手

组合文件读取、修改、命令执行和人工审批,让 Agent 修正一个文本文件并验证结果。工作区固定在示例脚本旁,便于查看实际变化。

准备环境

完成模型配置,从仓库根目录运行:

python examples/runtime/file_assistant.py

脚本会创建 examples/runtime/file-assistant-workspace/,仅在 notes.txt 不存在时写入初始内容。修改文件和运行验证命令之前,终端都会展示调用参数并等待确认。

完整示例

examples/runtime/file_assistant.py
"""Run a file-editing task with an explicit workspace and human approval."""

import asyncio
import json
import os
from pathlib import Path

import bumblehive
from bumblehive.console import ConsoleStreamRenderer


async def main() -> None:
    workspace = Path(__file__).resolve().parent / "file-assistant-workspace"
    workspace.mkdir(exist_ok=True)
    source = workspace / "notes.txt"
    if not source.exists():
        source.write_text("Bumblehive documantation\n", encoding="utf-8")
    print(f"工作目录:{workspace}")
    renderer = ConsoleStreamRenderer()

    async def approve_tool(
        request: bumblehive.ToolApprovalRequest,
    ) -> bumblehive.ToolApprovalDecision:
        if request.name in {"read_file", "list_dir", "find_files", "grep"}:
            return bumblehive.ToolApprovalDecision.approve()
        with renderer.pause():
            arguments = json.dumps(dict(request.arguments), ensure_ascii=False)
            answer = await asyncio.to_thread(
                input, f"允许 {request.name}({arguments})?[y/N] "
            )
        if answer.strip().lower() in {"y", "yes"}:
            return bumblehive.ToolApprovalDecision.approve()
        return bumblehive.ToolApprovalDecision.reject("The user rejected this operation.")

    config = bumblehive.RuntimeArguments(
        model=os.environ["BUMBLEHIVE_MODEL"],
        api_key=os.environ["BUMBLEHIVE_API_KEY"],
        base_url=os.environ["BUMBLEHIVE_BASE_URL"],
        workspace=workspace,
        tool_names=["read_file", "list_dir", "find_files", "grep", "edit_file", "exec"],
        max_iterations=8,
    )
    async with bumblehive.from_config(config) as runtime:
        result = await runtime.run_console(
            "读取 notes.txt,把拼写错误 documantation 改为 documentation。"
            "修改后再次读取文件,并运行一条 Python 命令检查拼写是否正确。"
            "如果审批被拒绝,不要尝试其他修改方式,直接说明未完成的步骤。",
            approval_handler=approve_tool,
            renderer=renderer,
        )
    if result.error:
        print(f"运行失败:{result.error.message}")
    print(f"最终文件内容:{source.read_text(encoding='utf-8').strip()}")


if __name__ == "__main__":
    asyncio.run(main())

观察运行结果

读取 notes.txt → 请求修改 → 用户确认 → 修改文件
                                      → 读取结果 → 确认验证命令 → 返回结果

批准修改后,最终文件内容应为 Bumblehive documentation。拒绝时检查原文件是否保留;不要只依赖模型声称“修改成功”。重复运行时文件可能已经修正,Agent 不一定再请求修改。

换成你的项目

将 workspace 改为项目目录,提示词改为具体任务。只读工具自动批准;示例对其他开放工具逐次确认。exec 可以启动真实进程,工作目录不构成进程沙箱。接入你的应用时,复用同一审批接口呈现命令和参数。

工具审批 · 文件与命令 · Runtime API