Module 6

Module 6: Task 自动化

构建能自动写代码、运行代码、从错误中学习的 Agent。

Python REPL错误自修正数据分析流水线安全机制

学习目标

构建能自动写代码、运行代码、从错误中学习的 Agent。


6.1 代码执行 Agent (code_execution_agent.py)

核心:Python REPL 工具


@tool
def python_repl(code: str) -> str:
    """执行 Python 代码并返回结果"""
    # 安全限制:只允许导入白名单中的模块
    stdout = io.StringIO()
    exec(code, {"__builtins__": __builtins__})
    return stdout.getvalue()

错误自修正循环


Agent 写代码 → 执行 → 报错 → Agent 读取错误 → 修复代码 → 重新执行 → 成功

这是 Agent 最令人惊叹的能力之一:它会自己 Debug!

安全机制

- 模块白名单:只允许导入 math, numpy, pandas 等安全模块

- 输出捕获:stdout/stderr 重定向

- 迭代上限:防止无限循环


6.2 数据分析流水线 Agent (data_pipeline_agent.py)

流程


数据加载 → 探索性分析 → 数据清洗 → 统计分析 → 可视化 → 报告

工具设计


@tool
def analyze_dataframe(code: str) -> str:
    """用 pandas 分析数据。变量 df 是当前数据集。"""

@tool
def generate_plot(plot_code: str) -> str:
    """生成 matplotlib 图表。"""

使用示例


用户: "加载 benchmark 数据,找出 mAP 最高的 3 个模型"
Agent:
  1. 调用 analyze_dataframe('print(df.nlargest(3, "mAP"))')
  2. 调用 generate_plot('df.plot.bar(x="model", y="mAP")')
  3. 给出分析结论

6.3 其他自动化 Agent 类型

网页浏览 Agent


@tool
def fetch_webpage(url: str) -> str:
    """抓取网页内容"""
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    return soup.get_text()

文件系统 Agent


@tool
def list_files(path: str) -> str:
    """列出目录文件"""

@tool
def read_file_content(path: str) -> str:
    """读取文件内容"""

Module 6 核心总结

能力 实现方式
代码执行 Python REPL tool + exec() + 输出捕获
错误自修正 错误信息反馈 → Agent 重写代码
数据分析 pandas tool + matplotlib tool
安全保护 模块白名单 + 操作确认 + 迭代上限