构建能自动写代码、运行代码、从错误中学习的 Agent。
构建能自动写代码、运行代码、从错误中学习的 Agent。
code_execution_agent.py)
@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 重定向
- 迭代上限:防止无限循环
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. 给出分析结论
@tool
def fetch_webpage(url: str) -> str:
"""抓取网页内容"""
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
return soup.get_text()
@tool
def list_files(path: str) -> str:
"""列出目录文件"""
@tool
def read_file_content(path: str) -> str:
"""读取文件内容"""
| 能力 | 实现方式 |
|---|---|
| 代码执行 | Python REPL tool + exec() + 输出捕获 |
| 错误自修正 | 错误信息反馈 → Agent 重写代码 |
| 数据分析 | pandas tool + matplotlib tool |
| 安全保护 | 模块白名单 + 操作确认 + 迭代上限 |