OpenClaw 企业定制 私人订制工作流 优化运维 openclaw记忆优化 问题咨询解决 请加微信交流
让AI写Python脚本调用工具,3步变1步。Code Execution是Hermes Agent最实用的功能之一——它让AI写Python脚本调用Hermes工具,把复杂的多步骤工作流压缩成一次调用。
这篇讲清楚Code Execution是什么、能做什么、以及实际使用场景。
Code Execution是什么
简单说:让AI写Python脚本,脚本里可以调用Hermes的所有工具(web_search、read_file、patch等),脚本运行完只返回print()的输出。
关键点:中间过程的工具结果不进入上下文,只有最后的print()输出才回来。这大大减少了Token消耗。
怎么工作
- AI写Python脚本,用
from hermes_tools import ...导入工具 - Hermes生成一个stub模块,里面是通过Unix域套接字RPC的函数
- 脚本在子进程里运行,工具调用通过套接字传回Hermes
- 只有脚本的print()输出返回给AI
from hermes_tools import web_search, web_extract
results = web_search("Python 3.13 features", limit=5)
for r in results["data"]["web"]:
content = web_extract([r["url"]])
# ... 过滤和处理 ...
print(summary)
什么时候用
当有这些情况时,AI会自动用execute_code:
- 3次以上的工具调用,且调用之间有处理逻辑
- 批量数据过滤或条件分支
- 循环遍历结果
可用工具
脚本里可以调用这些工具:
- web_search — 搜索网页
- web_extract — 提取网页内容
- read_file — 读文件
- write_file — 写文件
- search_files — 搜索文件内容
- patch — 补丁编辑
- terminal — 运行终端命令(仅前台)
实战例子
数据处理流水线
from hermes_tools import search_files, read_file
import json
# 找所有配置文件,提取数据库配置
matches = search_files("database", path=".", file_glob="*.yaml", limit=20)
configs = []
for match in matches.get("matches", []):
content = read_file(match["path"])
configs.append({
"file": match["path"],
"preview": content["content"][:200]
})
print(json.dumps(configs, indent=2))
多步网页研究
from hermes_tools import web_search, web_extract
import json
# 搜索、提取、总结,一次搞定
results = web_search("Rust async runtime comparison 2025", limit=5)
summaries = []
for r in results["data"]["web"]:
page = web_extract([r["url"]])
for p in page.get("results", []):
if p.get("content"):
summaries.append({
"title": r["title"],
"url": r["url"],
"excerpt": p["content"][:500]
})
print(json.dumps(summaries, indent=2))
批量文件重构
from hermes_tools import search_files, patch
# 找所有使用旧API的Python文件并修复
matches = search_files("old_api_call", path="src/", file_glob="*.py")
fixed = 0
for match in matches.get("matches", []):
result = patch(
path=match["path"],
old_string="old_api_call(",
new_string="new_api_call(",
replace_all=True
)
if "error" not in str(result):
fixed += 1
print(f"Fixed {fixed} files out of {len(matches.get('matches', []))} matches")
构建测试流水线
from hermes_tools import terminal
import json
# 运行测试,解析结果,报告
result = terminal("cd /project && python -m pytest --tb=short -q 2>&1", timeout=120)
output = result.get("output", "")
passed = output.count(" passed")
failed = output.count(" failed")
errors = output.count(" error")
report = {
"passed": passed,
"failed": failed,
"errors": errors,
"exit_code": result.get("exit_code", -1),
"summary": output[-500:] if len(output) > 500 else output
}
print(json.dumps(report, indent=2))
资源限制
| 资源 | 限制 | 说明 |
|---|---|---|
| 超时 | 5分钟(300秒) | 超时后SIGTERM,5秒后SIGKILL |
| stdout | 50KB | 超出截断 |
| stderr | 10KB | 非零退出时包含在输出里 |
| 工具调用 | 50次/每次执行 | 达到后报错 |
可在config.yaml里调整:
code_execution:
timeout: 300
max_tool_calls: 50
工具调用怎么在脚本里工作
当脚本调用一个函数(如web_search(“query”))时:
- 调用被序列化为JSON,通过Unix域套接字发送到父进程
- 父进程通过标准handle_function_call处理
- 结果通过套接字发回
- 函数返回解析后的结果
这意味着脚本里的工具调用和普通工具调用行为完全一致——相同的速率限制、相同的错误处理、相同的 capabilities。唯一限制是terminal()只有前台模式(不支持background/pty/check_interval参数)。
错误处理
脚本失败时,AI收到结构化错误信息:
- 非零退出码:stderr包含在输出里,AI能看到完整traceback
- 超时:AI看到”Script timed out after 300s and was killed.”
- 中断:用户发新消息时脚本终止,AI看到”[execution interrupted — user sent a new message]”
- 工具调用超限:第50次之后每次调用返回错误
安全模型
子进程在最小化环境中运行。默认情况下API密钥、令牌、凭据都会被剥离。脚本只能通过RPC通道访问工具,不能读取环境变量中的密钥。
包含这些关键词的环境变量会被过滤:KEY、TOKEN、SECRET、PASSWORD、CREDENTIAL、PASSWD、AUTH。只传递安全系统变量(PATH、HOME、LANG、SHELL等)。
Skill环境变量透传
当Skill在前言里声明了required_environment_variables,这些变量会自动透传到execute_code和terminal沙箱。
手动透传
terminal:
env_passthrough:
- MY_CUSTOM_KEY
- ANOTHER_TOKEN
execute_code vs terminal
| 场景 | execute_code | terminal |
|---|---|---|
| 多步骤工具调用流程 | ✅ | ❌ |
| 简单shell命令 | ❌ | ✅ |
| 过滤/处理大输出 | ✅ | ❌ |
| 运行构建或测试 | ❌ | ✅ |
| 循环遍历搜索结果 | ✅ | ❌ |
| 交互式/后台进程 | ❌ | ✅ |
| 需要环境变量中的API密钥 | ⚠️ 只能透传 | ✅ |
平台支持
Code Execution依赖Unix域套接字,只支持Linux和macOS。Windows自动禁用,AI回退到普通顺序工具调用。
实际使用场景
批量SEO内容分析
用execute_code批量分析关键词搜索结果,提取内容摘要,一次性拿到所有需要的数据。
代码库批量修改
找出所有使用旧API的文件,一次性全部替换。不用一个一个手动改。
自动化测试报告
运行测试套件,解析输出,生成格式化报告。比手动跑测试看结果高效得多。
数据采集管道
搜索→提取→处理→总结,全自动。适合做竞品分析、市场调研。
常见问题
脚本里能调用多少次工具?
默认50次,超过后返回错误。可以在config.yaml里调整。
脚本能访问我的API密钥吗?
默认不能。包含KEY/TOKEN/SECRET/PASSWORD等关键词的变量会被过滤。如果需要,用env_passthrough透传。
脚本运行多久会被强制终止?
默认5分钟。可以配置timeout调整。
脚本出错了我怎么知道?
错误信息通过stderr返回给AI,AI会告诉你出了什么问题。
Windows能用吗?
不能。Code Execution需要Unix域套接字,Windows不支持。Windows用户AI会回退到普通顺序工具调用。
总结
Code Execution让Hermes Agent真正具备了”写代码完成任务”的能力。
核心价值:
- 多步骤工具调用压缩成一次执行
- 中间结果不进上下文,节省Token
- 适合批量处理、自动化流水线
- 安全沙箱环境,密钥不泄露
- Linux/macOS支持,Windows自动禁用
建议配合Search和web工具一起用,做批量研究和数据处理特别高效。








暂无评论内容